Reputation: 2180
I am trying to add ajax in my laravel 5.2 project for some days but I have not been able to. I need help/link/tutorial from anybody. Note that I googled many times in the mean time and follow the mentioned process but nothing happened.
Here's a piece of my code: Ajax:
$('#contact-sort').on('click', function () {
//$this = $(this);
// alert($this.data('id'));
$.ajax({
method: 'post',
url: '/abc',
data: {id: 'id'},
success: function (msg) {
alert(msg);
}
})
})
Route:
Route::post('/abc', function (Request $request) {
return $request->id;
});
Here's an image of my network panel
Screenshot of Network panel at Firefox
Upvotes: 0
Views: 174
Reputation: 5452
In Laravel 5.2 all HTTP requests goes through web middleware so you need to pass CSRF token in your Ajax header.
Put this on your js file where you perform your ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
and this one goes to your master page or necessary HTML/blade page(put it between head tags)
<meta name="csrf-token" content="{{ csrf_token() }}">
More information could be found here https://laravel.com/docs/master/routing#csrf-protection
Upvotes: 0
Reputation: 2180
It was because:
In Laravel:
I copied the .htaccess file from public folder to the root folder and renamed the server.php file to index.php. So my public folder is one step up. Hence url:'/abc' was not found in the server. I make the url one step up by adding two periods before the slash like url:'../abc' and problem has been solved.
Upvotes: 0
Reputation:
It may be helpful to open up Google Chrome and trace the network request.
Something to bare in mind when using Laravel and AJAX, you need to pass a _token with the AJAX request if you're using either an auth
or web
middleware.
$.ajax({
method: 'post',
url: '/abc',
data: {
id: 'id',
_token: "{{ csrf_token() }}"
},
success: function (msg) {
alert(msg);
}
});
Please screenshot your network panel request, this will be a lot of help!
Upvotes: 1