You need to set the jQuery AJAX headers to include the token - see http://laravel.com/docs/5.0/routing#csrf-protection under X-CSRF-TOKEN.
Why am I getting this TokenMismatchException ?
So I'm working my way through the Build Your First App series. I'm on the final video in which, amongst other things, Jeff shows us how to use a sub-form and AJAX to update the database without a page refresh.
I'm updating a simple boolean field in the database to say whether a listed recipe has been made or not. Here's my form code:
{!! Form::open(['data-remote','method' => 'PATCH', 'url' => 'recipes/' . $recipe->id]) !!}
<div class="form-group">
{!! Form::checkbox('recipe_made',$recipe->recipe_made,$recipe->recipe_made)!!}
{!! Form::submit('Submit') !!}
</div>
{!! Form::token()!!}
{!! Form::close() !!}
(I added the Form::token() to try and fix the problem, no dice)
Here is the Javascript that listens for the form submission etc:
'use strict';
(function ($) {
var o = $({});
$.subscribe = function () {
o.on.apply(o, arguments);
};
$.unsubscribe = function () {
o.off.apply(o, arguments);
};
$.publish = function () {
o.trigger.apply(o, arguments);
};
})(jQuery);
(function () {
var submitAjaxRequest = function submitAjaxRequest(e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST'; // find the hidden method field that laravel adds, otherwise default to POST
console.log(method);
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize,
success: function success() {
$.publish('form.submitted', form);
}
});
e.preventDefault();
};
//forms marked with data-remote will submit via Ajax
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
(function () {
$.subscribe('form.submitted', function () {
$('.flash').fadeIn(500).delay(1000).fadeOut(500);
});
})();
//# sourceMappingURL=all.js.map
This successfully triggers and logs the correct method for the database update (ie PATCH).
However, on watching the submission in the Network tab in Chrome, I get the following 500 error:
TokenMismatchException in VerifyCsrfToken.php line 46:
This happens even if I carry out the submission as soon as I log in, so it can't be the login timing out. What's odd is that Jeff doesn't seem to encounter the error. Conspiracy! ;)
Any ideas?
Please or to participate in this conversation.