jrgilman
jrgilman

Reputation: 483

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

Upvotes: 8

Views: 5807

Answers (3)

Pri Nce
Pri Nce

Reputation: 711

Here is the solution that worked for me.

var xhr = new XMLHttpRequest();
xhr.open('POST', group_email_url, true);
xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var data = JSON.parse(xhr.responseText);
      if (data['status']==true) {
         window.location = group_list_url;
      } else {
         alert('Whoops Something went wrong!!');
        }
      }
     }
xhr.send('group_id=' + group_id + '&ids=' + strIds);

Upvotes: 0

Codedreamer
Codedreamer

Reputation: 1702

If you're still struggle with the above answer, You can try this below.

var token = $("#token").val();
const xhr = new XMLHttpRequest();
xhr.open("POST", "upload/media/files?_token="+token);

While the $("#token).val() is already inside a hidden input see example below.

<input type="hidden" id="token" value="{{ csrf_token() }}" name="token">

Upvotes: 0

jrgilman
jrgilman

Reputation: 483

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.

Upvotes: 3

Related Questions