Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 xmlHttpRequest AJAX POST TokenMismatchException

The relevant code is shown below:

var csrfToken = "{{ csrf_token() }}";
xmlhttp.open("POST", "/internal/v1/create/strategy", true);
xmlhttp.setRequestHeader('X-CSRF-TOKEN', csrfToken);
postString = "param1=" + varOne + "&param2=" + varTwo;
xmlhttp.send(postString);

I've been trying to figure this out for hours now, I honestly have no idea what to do at this point. Note, that if I use the form method everything works just fine. I've also tried sending the CSRF token as a parameter in the postString: "_token=" + csrfToken

like image 465
jrgilman Avatar asked Oct 25 '15 04:10

jrgilman


1 Answers

The problem was resolved via a two-part solution:

It was necessary to add the 'Content-type' header for the Laravel to be able to read the POST'ed parameters:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Additionally, in the config/session.php file it was necessary to also point the 'domain' variable towards the actual domain of the application, rather than the default value of null. This is probably something that's done during initial setup, but I must have forgot to do so.

After making both of these changes, the POST request would successfully go through via AJAX calls.

like image 153
jrgilman Avatar answered Nov 09 '22 03:11

jrgilman