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

zachleigh's avatar

Ajax token mismatch (vanilla javascript)

Im trying to send post data through ajax (no jquery), but keep getting token mismatches. I have this tag in my html:

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

Ive tried to send the _token value both in the header and within the send() brackets, but nothing seems to be working. How do I send the token so that Laravel will pick it up correctly?

0 likes
3 replies
otepas's avatar

Have you checked that the input "_token" gets to the server?

I have only done it with jQuery, and the code was something like this:

// Get the token value from the hidden form
token = $('input[name="_token"]').val();
// Send the ajax request
$.ajax({
    method: "POST"
    url: '/request/url',
    data: {_token: token, other_param: value}
});

(I'm writing off memory, so the code might not be 100% correct)

1 like
christopher's avatar

Put this in your jQuery before you make any requests. It will automatically insert your token on every request:

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

Then in your CSRF middleware add this before return parent::handle($request, $next):

if($request->ajax())
{
    \Input::merge([
        '_token' => $request->header('X-CSRF-Token')
    ]);
}
1 like
zachleigh's avatar
zachleigh
OP
Best Answer
Level 47

Figured it out. I needed to set content type in the request header

    var token = document.getElementsByTagName('input').item(name="_token").value;
    var data = "_token="+token;

    xmlhttp.open("POST", "ajax/myFunction", true);
    xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(data);

Thanks for the suggestions. They pointed me in the right direction.

Please or to participate in this conversation.