Furya
Furya

Reputation: 463

Laravel 5.6 Ajax post data

I tried to send data to a page with Ajax post without form but it doesn't work.

I guess my problem come from crs but I won't be able to find how to make it work.

In the header of my page, I have ;

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

Then, for this example, I have a datatable with reorder plugin. When reorder event is trigger, I use Ajax call (but my problem happen no matter what I do to send post Ajax except with form).

table{{$batiment->id}}.on( 'row-reorder', function ( e, diff, edit )      {
   $.ajaxSetup({
headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

    $.ajax({
        url: 'etages/form',
        type: 'POST',
        data: {item_id : 1},
        dataType: 'json',

        success: function( data ) {
            console.log(data);

        }       
    })
});

My route to form :

Route::post('/etages/form', ['as' => 'etages.form', 'uses' => 'Copro\EtageController@form']);

And my function form from my controller (this function work well with form post data) :

public function form(Request $request)
{

    $request->flash();

    return response()->json([
        'error' => 'false'
    ]);
}

But every time I tried post data without form, no matter what trigger I use (datatable, onclick...) I have this message :

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message

On chrome console I can see my post data, but on laravel's error page, post data is empty. I don't know if it's normal.

Someone can help me with that problem ? I can't always use get to send this kind of data.

Thank for your help.

Upvotes: 2

Views: 9009

Answers (2)

Deepesh
Deepesh

Reputation: 102

your link 'etages/form' , have you defined it in a api route. if you have defined in a api route, then it should be like this '/api/etages/form'.

Upvotes: 1

Amin Fazlali
Amin Fazlali

Reputation: 1237

Method 1:

var csrf = $('meta[name="csrf-token"]').attr('content');
$.ajax({
    url: '/etages/form',
    type: 'POST',
    data: {item_id : 1, '_token': csrf},
    dataType: 'json',

    success: function( data ) {
        console.log(data);

    }       
})

Method 2:

$.ajaxSetup({
headers: {
    'X-XSRF-TOKEN': decodeURIComponent(/XSRF-Token=([^;]*)/ig.exec(document.cookie)[1])
}
});

$.ajax({
    url: '/etages/form',
    type: 'POST',
    data: {item_id : 1},
    dataType: 'json',

    success: function( data ) {
        console.log(data);

    }       
})

Upvotes: 4

Related Questions