-2

CSRF token mismatch in laraval 8, token code added to meta tag and this simple ajax not working,

Md. Rejaul Karim
  • 115
  • 1
  • 1
  • 10
JBN
  • 7
  • 2
    show some code where you get error like ajax code ,route for that request etc.. – John Lobo May 29 '21 at 15:35
  • function runtest() { var id="1"; var token = $('meta[name="csrf-token"]').attr('content'); $.ajax({ type: "POST", data: {"_token": token,"id": id}, url: "{{url('some_url')}}", success: function(msg){ // do whatever you want with the response } }); } – JBN May 29 '21 at 15:36
  • above shows ajax code – JBN May 29 '21 at 15:36
  • Is that the answer you're looking for? https://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request – omar esmaeel May 29 '21 at 15:39
  • once you try clearing php artisan view:clear then php artisan key:generate and then serve again.i have tried your ajax and it works expected so – John Lobo May 29 '21 at 15:43
  • also verifiy by alerting token whether you get value or not – John Lobo May 29 '21 at 15:44
  • both clear view and key regenerated done, but ""message": "CSRF token mismatch.", – JBN May 29 '21 at 15:56
  • yes, also verifiy by alerting token whether you get value or not = > value showing – JBN May 29 '21 at 15:56
  • 1
    Hello, please remember to post code as text rather than pictures. Details about the reasons why are in this post: https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors – morric May 31 '21 at 09:57

2 Answers2

0

Add headers key after success key:

        success: function(msg){
           //do whatever you want with the response
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }

and in views\layouts\app.blade.php add this line:

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

Add headers key after success key:

    success: function(msg){
       //do whatever you want with the response
    },
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }

and in views\layouts\app.blade.php add this line: