prgrm
prgrm

Reputation: 3835

AJAX Post request not working with Laravel

I can do this:

 $.ajax({
        type: "GET",
        async: true,
        url: '/someurl/',
        dataType: 'json',
        success: function (data) {
            console.log(data);
        }
    });

Web:

Route::get('/someurl','MyController@myfunction');

And it works just fine, but when I try the same with post:

 $.ajax({
        type: "POST",
        async: true,
        url: '/someurl/',
        dataType: 'json',
        success: function (data) {
            console.log(data);
        }
    });

Route::post('/someurl','MyController@myfunction');

I get a 405 method not allowed error message in the console

Upvotes: 0

Views: 85

Answers (2)

Jigs1212
Jigs1212

Reputation: 773

Add another route with

Route::post('/someurl','MyController@myfunction');

By the way u are not sending any data, in post we need to send data right..

Also check whether csrf token is being passed in data, if not as mentioned above try adding it manually.

If you are using {{Form...}} it would be automatically added to form data.

Upvotes: 1

ZeroOne
ZeroOne

Reputation: 9117

POST using normal ajax need CSRF Token to be pass in POST Method

in your ajax

 $.ajax({
        type: "POST",
        async: true,
        url: '/someurl/',
        dataType: 'json',  
        data : {"_token":"{{ csrf_token() }}"}  //pass the CSRF_TOKEN()
        success: function (data) {
            console.log(data);
        }
    });

or

set head meta tag

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

set header ajax

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

Upvotes: 2

Related Questions