I'd double check that you're sending in the token correctly.
Ajax request -> server status 500 -> TokenMismatchException
I have two selects in the form, where options of the second one are dependant on value of first one (when user choose animal type in the first select, second one needs to be updated with appropriate list of breeds)
So here is the code:
- within the view:
$('select[name="animal_id"]').change(function() {
var animal_id = $(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
$.ajax({
type: 'post',
url: '{{ route("dashboard::pets::getBreed") }}',
data: animal_id,
success: function(data) {
alert('$data = ' + data);
}
});
});
- routes.php
Route::group(['middleware' => ['web']], function () {
/* Routes for admin dashboard */
Route::group(['prefix' => 'dashboard', 'as' => 'dashboard::'], function() {
(...)
/* Manage pets */
Route::group(['prefix' => 'pets', 'as' => 'pets::'], function() {
(...)
/* Ajax requests */
Route::post('ajax/getbreed','PetsController@ajaxGetBreed')->name('getBreed'); // Route name: dashboard::pets::getBreed
(...)
});
(...)
});
});
- PetsController.php
/** Ajax requests **/
public function ajaxGetBreed() {
$data = 'it works!';
return $data;
}
when value of first select (name='animal_id') is changed the effect (seen in console) is as follows:
"Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://dogsandthecity.dev/dashboard/pets/ajax/getbreed" with extra info: "TokenMismatchException" that can be seen in "resources" tab of Safari's dev tool.
What am I doing wrong?
Thanks!
If you want to put the CSRF token in the meta tag, make sure you put the following within the <head> tags (in your layout template):
<meta name="_token" content="{!! csrf_token() !!}" />
You might have missed this in the tutorial because the meta tag was included at the bottom along with the scripts!
Good luck!
Please or to participate in this conversation.