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

simonjolsen89's avatar

Debug 419 Page Expired on Ajax post

I'm having issues posting with ajax, and I'm getting 419 Page expired errors.

At first glance, this is most likely because of a token mismatch. However, I've made sure I have

<meta name="csrf-token" content="{{ csrf_token() }}">

In my header.

And in my ajax post

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

  $.ajax({
      type: 'post',
      url: 'addtocart',
      headers: headers, 
......

When I log the token in the ajax, it matches what's in my header, so I'm not really sure what's going on. Any suggestions?

0 likes
8 replies
Nakov's avatar

Have you tried adding it once using:

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

and btw, the token mismatch can be because the session expired in case the user is sitting on the page for more than 30 minutes for example. So make sure in your ajax response you handle the 419 error.

simonjolsen89's avatar

@Nakov Even with the ajaxSetup I'm getting the 419. It's don't think it's because the session expires, since this happens everything, even on a newly refreshed session

folium's avatar

@simonjolsen Try Something like this...

var _token = $("input[name='_token']").val();

 $.ajax({
         url: 'addtocart',  
         type:'POST',
         data: {_token:_token},
         success: function(data) {
             //whatever you want
         }
   });
folium's avatar

@simonjolsen if you are performing it in blade file , you can do something like this also..

$.ajax({
         url: 'addtocart',  
         type:'POST',
         data: {_token:"{{ csrf_token() }}"},
         success: function(data) {
             //whatever you want
         }
   });
simonjolsen89's avatar

@folium Still same issue.

Is there any config files that could have some wrong settings or? Seems like it doesn't matter how I try to post the token.

Please or to participate in this conversation.