Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax Post to Laravel - CSRF Token Mismatch

I am trying to post data to Laravel backend with ajax, however I am getting 'CSRF token mismatch' error.

First, I've placed token in html (in body but outside its form because it's not the whole form, its only 2 elements to be posted):

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

Then in 'document ready', I try to post the data with ajax.

data["_token"] = jQuery('#token').val();  

// Also tried this:
jQuery.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': jQuery('#token').val()
       }
})

console.log(data) // returns the array with _token: "esOKmY8Tpr4UvhTYMhWcWui0rpvYEjJ3es7ggics"

jQuery.ajax({
     type: "POST",
     url: '/my-route',
     data: data,
     success: function() {
          console.log("A");
     }
});

The data which I want to post are little chunk of a bigger form, and with using this approach, I can autocomplete form. The little chunk of html inputs are not inside any other sub-form. Maybe this can be the case?

- Form:
- A: bla // to be posted
- B: hello  // to be posted
- C: smt else // no post

but getting the values are working okay

Route:

Route::post('/my-route', 'AdminController@theFunction')->middleware('admin');


Edit: I changed <input> to <meta> tag

like image 714
senty Avatar asked Sep 16 '16 20:09

senty


People also ask

How do I disable CSRF protection in laravel?

Laravel Disable CSRF Token Protection To disable CSRF protection on all routes. So navigate to app\Http\Middleware and open VerifyCsrfToken. php file. Then update the routes, which you want to disable CSRF protection.

What causes CSRF token mismatch?

Invalid or missing CSRF token This error message means that your browser couldn't create a secure cookie, or couldn't access that cookie to authorize your login. This can be caused by ad- or script-blocking plugins, but also by the browser itself if it's not allowed to set cookies.


2 Answers

I had the same problem try to put include CSRF tag in your meta like so

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

and read it in your ajax code like so :

<script type="text/javascript">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
</script>

Last Update

Please modify your url variable like so :

jQuery.ajax({
    type: "POST",
    url: '/my-route'+'?_token=' + '{{ csrf_token() }}',
    data: data,
    success: function() {
         console.log("A");
    }
  });
like image 197
Nour Avatar answered Oct 16 '22 18:10

Nour


Try This


    var formData = new FormData();
    formData.append("_token", "{{ csrf_token() }}");
    $.ajax({
    headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
    },
    url: 'save_search',
    data: formData,
    processData: false,
    type: 'POST',
    success: function ( data ) {
    alert( data );
    }
    });

like image 2
Keshav Joshi Avatar answered Oct 16 '22 18:10

Keshav Joshi