2

I am having difficulty getting an ajax post to work with laravel v5.5.24. Here is what my ajax call looks like:

var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
    url: "/postCustomer?XDEBUG_SESSION_START=19683",
    type: 'POST',
    data: {_token: CSRF_TOKEN, message:myData, "_method": 'POST'},
    dataType: 'JSON',
    success: function (data) {
        console.log('call to postCustomer successful');
    }
});

Here is my route:

Route::post('/postCustomer','AdminUserController@store');

The interesting thing about this problem is that when all the post's are changed to get's (both in the ajax call and in the route) the request arrives and is handled correctly. The debug is triggered, and all is well. However, iof the route and the ajax call is set to POST, the debug is never triggered, and the request does not appear to make it. Naturally this smells like a CRSF issue, but I am including the CRSF token in the header.

George Pipkin
  • 21
  • 1
  • 3
  • You shouldn't have to pass the `_token` inside the data object. The CSRF token is automatically added into the header via `$.ajaxSetup()`. Could you post a screenshot of the network request? – Nick Tucci Dec 21 '17 at 04:39
  • can you post your code inside your form's tag? – Jems Dec 21 '17 at 05:05
  • Hav you checked console ? – Bugfixer Dec 21 '17 at 05:23
  • 1. You have the token as `CSRF_TOKEN`, you can use that in your `ajaxSetup()`, no need to look it up from the meta tag again. 2. You send the token in `ajaxSetup()`, no need to send it again in your `data`. 3. You only need to include `_method` when you are doing `PATCH`, `DELETE` etc - don't use it for plain `POSTs`. 4. Probably not important, but [AFAIK the `dataType` should be lower case](http://api.jquery.com/jquery.ajax/) - ie `json`. 5. Finally, what is the actual problem? Do you see the request/response in devtools, do they look OK? What about `storage/logs/laravel.log`? – Don't Panic Dec 21 '17 at 10:08
  • Chech this : https://stackoverflow.com/questions/53684928/how-to-automatically-add-x-csrf-token-with-jquery-ajax-request-in-laravel – Prateek Dec 08 '18 at 17:22

4 Answers4

0

if the javascript code inside .blade.php file try this

 data: {_token:'{{ csrf_field() }}', message:myData, "_method": 'POST'},

hope its help

R . dwj
  • 108
  • 6
  • what error did you get? is the url correct? i usually do this on the URL: url: "{{ url('postCustomer') }}"+'?'+'XDEBUG_SESSION_START=19683', – R . dwj Dec 21 '17 at 04:54
0

Try this, <meta name="_token" content="{!! csrf_token() !!}"/>

$.ajaxSetup({
        headers:
            {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
    });
$.ajax({
    url: "/postCustomer?XDEBUG_SESSION_START=19683",
    type: 'POST',
    data: {message:myData, "_method": 'POST'},
    dataType: 'JSON',
    success: function (data) {
        console.log('call to postCustomer successful');
    }});

No need to pass token in ajax data again.

0

Heartfelt thanks to everyone who responded. A couple of things helpled in fuguring this thing out. First of all, I consolidated the CSRF token mentions, and confined what I was sending as data to just that - no need to include the CSRF token in the data if you do it in the ajaxSetup. The second thing wasn't visible from my post, but I was encountering a race condition involving the button that triggered the ajax transaction. The button was causing a page reload before ajax could do its thing, and this is why occasionally the thing would appear to work, but mostly not. So the return false is necessary to prevent that - probably not in both places, but certainly after the ajax transaction has been invoked and we are waiting for the callback. The code which works can be found below. I hope it will prevent somebody else from spending a night going mad trying how to figure out what their POST's aren't working. Take away points: handle your CSRF in an ajaxSetup call, and return false from the whole business.

Thanks again to everybody.

-George Pipkin Afton, Virginia

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                $.ajax({
                    /* the route pointing to the post function */
                    url: "/postCustomer?XDEBUG_SESSION_START=19159",
                    type: 'POST',
                    /* send the csrf-token and the input to the controller */
                    data: {message:myData},
                    dataType: 'json',
                    /* remind that 'data' is the response of the AjaxController */
                    success: function (data) {
                        $("#success_msg").show();
                        return false;
                    }
                });
                return false;
George Pipkin
  • 21
  • 1
  • 3
0

You should have to pass the _token inside the data object.

data: {_token:'{{ csrf_token() }}',, message:myData, "_method": 'POST'},
Dharman
  • 30,962
  • 25
  • 85
  • 135