Shwe Myatmon
Shwe Myatmon

Reputation: 21

How to use POST method in laravel and ajax

When I use a POST method with the following ajax request, it throws a "Method not allowed" error. If I use the form POST without using ajax, it goes to the proper method.

In Router.php:

 $this->post('TestPost','DashboardController@TestPostMethod');

In View, the ajax request is:

$.ajax(
{           
type: "POST",
url: 'TestPost',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {  
alert('hid post');       

SetHotandWorstData(data,'hotquantity');

},

error: function (msg) {
alert('error');
alert(msg.responseText);
}
});

In Controller:

function TestPostMethod(Request $request)
{
    $hotworstsalesdata = DB::table('100_INVOICEDETAIL')              
    ->select( '100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME',
DB::raw('SUM("100_INVOICEDETAIL"."QTY") as 
salesqty'), DB::raw('SUM("100_INVOICEDETAIL"."AMT") as salesamt'))
    ->groupBy('100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME')
    ->orderBy('salesqty')
    ->take(10)
    ->get();
    return Datatables::of($hotworstsalesdata)->make(true);
}

Upvotes: 0

Views: 483

Answers (2)

Rajinder
Rajinder

Reputation: 1091

you should pass "_token" in POST data. Laravel use token for cross-site request forgery (CSRF) attacks. use following code in your AJAX request

data: { _token: "{{ csrf_token() }}"  }

Updated answer:

I have re-create same scenario on my system with laravel 5.4 and it's working for me.

my route (web.php) code is:

Route::post('/test_post', 'DashboardController@getData');

Javascript code is:

<script type="text/javascript">
    $.ajax({
        type: "POST",
        url: '{{ url('/') }}/test_post',
        data: { _token: "{{ csrf_token() }}"  },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            console.log(data);
        },

        error: function (msg) {

            console.log(msg.responseText);
        }
    });
    </script> 

DashboardController file is:

public function getData(Request $request) {
    print_r($request);      
}

Upvotes: 4

Jack jdeoel
Jack jdeoel

Reputation: 4584

Recently I got error with DELETE method ! I fixed by setting csrf token in html header and get in ajax . Hope this can solve your problem ..

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

In ajax,

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

Upvotes: 0

Related Questions