Search code examples
ajaxlaravelcsrflaravel-6.2csrf-token

Laravel CSRF token mismatch exception. Sending "Put" request to a resource route via jQuery ajax


I am in a need to send a PUT request to a resource Route defined as :

Route::resource('posts','PostController');

My code works fine like this :

            var data = $(this).serializeArray();
            data.push( {name:'_token',value:"{{ csrf_token() }}" })
            $.ajax({
                type: "Put",
                url: _url,
                data: data,
                dataType: "json",
                success: function (response) {
                    if(response.status){
                        toastr.success(response.msg);
                    }
                    else{
                        toastr.warning(response.msg);
                    }
                },
            });

But the problem comes when i am having to send files through the route, for that i had to modify my submit function as :

          var data = new FormData(this);
          data.append("_token","{{ csrf_token() }}");
          var _url = $(this).attr('action');
          $.ajax({
            type: "Put",
            url: _url,
            data: data,
            dataType: "json",
            processData:    false,
            contentType:    false,
            success: function (response) {
              if(response.status){
               toastr.success(response.msg);
              }
            }

I hit a exception with message "CSRF token Mismatch". Is this because I used FormData() ?


Solution

  • Add the csrf in your blade

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

    And then send it via headers to avoid it sending by appending it data

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

    And remove this line data.append("_token","{{ csrf_token() }}"); and try