Samar Preet Samar Preet - 4 months ago 26
Javascript Question

How to get Laravel 5.2 token in every AJAX Post Call?

I'm trying to get laravel token in every AJAX Post request because I haven't using laravel form so no token automatically retrieved.

HTML BODY:

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


My code:

function ajax_Call() {
var formdata = $("form").serializeArray();
token = $('#_token').val();
$.ajax({
url: 'url',
type: 'POST',
token: token;
data: formdata,
success: function (r) {
}
});
}


But its not working.Please help me.

Answer

Add token to formData instead AJAX parameter:

function ajax_Call() {
    var formdata = $("form").serializeArray();
    formdata.append("_token", $('#_token').val());
    $.ajax({
        url: 'url',
        type: 'POST',
        data: formdata,
        success: function (r) {
        }
    });
}

Will also Send token through headers:

$.ajaxSetup({
    headers: {
        'X-CSRF-Token': $('#_token').val()
    }
});
Comments