Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ejay010's avatar

Trying to make an ajax request, using laravel 5

Hello all, I have been trying to figure out this thing for a while. I am just learn how to use this ajax with jquery. But for some reason, every step I make forward, I end up taking two steps back. First I was getting a csrf error, fixed that by making a meta tag with the csrf token and then pulling it into the ajax request. Here is my request now: http://snag.gy/HIcGl.jpg

Now I am getting a different error, something about decryption. Am thinking that laravel, for some reason can't decrypt the token now. looking at the decryptor class it indicates that the token that I am sending is not valid Json data. So confused now. Now it doesn't like the token I sent it... any way here is my error http://snag.gy/lyGcg.jpg

Also I am using phpStorm with laravel 5

0 likes
8 replies
AkarM13's avatar
AkarM13
Best Answer
Level 2

Why don't you send the _token along with other form variables? For example:

    $.ajax({
        url: 'somewhere',
        data: {message: 'Hello!', _token: $('input[name=_token]').val()}
    });

Let me know if this fixed your issue.

1 like
bestmomo's avatar

As @AkarM13 said it's easy to send token in data. Here an example :

$(document).on('change', ':checkbox[name="active"]', function() {
  ...
  var token = $('input[name="_token"]').val();
  $.ajax({
    url: 'postactive/' + this.value,
    type: 'PUT',
    data: "active=" + this.checked + "&_token=" + token
  })
  .done(function() {
    ...
  })
  .fail(function() {
    ...
  });
});
ejay010's avatar

@AkarM13 you sir...are a genius.

But for all the gurus out there that will come across this in the future my question now is why is it that I must pass the token variable in the data field. Shouldn't it suffice to pass it in the header field?

In case your curious here is what my ajax looks like now: http://snag.gy/LC6XL.jpg

bestmomo's avatar

Define as it is said in documentation :

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

And it will work, take care with CSRF typo.

Please or to participate in this conversation.