I am trying to achieve a simple create form using ajax
The data is saved to the database, but the problem is that after submit, the page redirects to the same URL with the variables added in it
example: 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);
}
});
Notice the alerts in success function: 1- The first is displayed 2- The second one is not displayed, nor the toastr
I even tried adding a link and triggering the click function that redirects to the index page but it doesn't work
Any help?