表单提交后,它会重定向到同一页面

时间:2017-12-28 14:45:50

标签: php jquery ajax laravel-5.5

我正在尝试使用ajax实现一个简单的创建表单 数据保存到数据库,但问题是提交后,页面重定向到相同的URL,其中添加了变量 例如:localhost/items/create?_token=1r42dIWXc4oirlJ2gGbEWgZL1I32L6FefVdmy3zy&_token=1r42dIWXc4oirlJ2gGbEWgZL1I32L6FefVdmy3zy&txtName=kjsjksjksk&txtAmount=8202

web.php

Route::group(['middleware' => ['web']], function(){
    Route::get('/items', 'ItemController@index')->name('items');
    Route::get('/items/create', 'ItemController@create')->name('itemcreate');
    Route::POST('/items/store', 'ItemController@store')->name('itemstore');
});

ItemController

public function create()
{
    $customers = \App\Customer::all();
    return view("items.create")->with('customers', $customers);
}

public function store(Request $req)
{
    $item = new \App\Item;
    $item->name = $req->name;
    $item->details = $req->details;
    $item->total_amount = $req->total_amount;
    $item->customer_id = $req->customer_id;

    $item->save();

    return ['redirect' => route('items')];
}

create.blade.php

        $.ajax({
               type: 'POST',
                url: 'store',
                data: {
                    '_token': $('input[name=_token]').val(),
                    'name': $('input[name=txtName]').val(),
                    'details': $('textarea#txtDetails').val(),
                    'total_amount': $('input[name=txtAmount]').val(),
                    'customer_id': $('#customer').val(),
                },
                success: function (data){
                    //window.location = response.data.redirect;
                    alert("success");
                    // toastr.success('Workshop added successfully');
                    // setTimeout(function(){
                         alert("after timeout");
                    // }, 1000);
                }
            });  

注意成功功能中的警报: 1-显示第一个 2-没有显示第二个,也没有显示toastr

我甚至尝试添加链接并触发重定向到索引页面的点击功能,但它不起作用

任何帮助?

1 个答案:

答案 0 :(得分:2)

假设您的表格类似于

ArgumentOutOfRangeException

您使用<form action="someAction" method="POST"> <input.../> <button id="button" type="submit"...>Submit</button> </form> 事件。例如

onclick

现在,您可以在$('#button').on('click', function() { //your code }); 中将event作为参数传递,并使用function()方法。例如:

preventDefault()

它将停止提交按钮的默认行为。

相关问题