Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method not allowed when PUT used over AJAX for Laravel resource

I've got this resource in routes.php:

Route::resource('items', 'ItemsController', ['before' => 'admin_access']);

Trying to reach ItemsContoller@update method through AJAX but it's kicking out a 405 Method not allowed error:

var $inputs = $('input', row);

var id = $(row).find('.edit').data('id');

var data = $inputs.serializeJSON();

data['_token'] = $('input[name=_token]').val();
data['_method'] = 'PUT';

console.debug(data);

$.ajax({
    url: 'items/' + id,
    method: 'PUT',
    dataType: 'json',
    data: data,
    complete: function (data) {
        if (data.success) {
            itemsTable.ajax.reload();
        }
    }
});

Both the id and data variables contain the correct information.

This works fine when I do a standard form submission with PUT as the method (using anahkiasen/Former opener method).

What am I missing here?

like image 793
eComEvo Avatar asked Jul 25 '15 21:07

eComEvo


People also ask

What is the use of ajax () method?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

How do I know if ajax is working in Laravel?

In Laravel, we can use $request->ajax() method to check request is ajax or not.

Where do I put ajax code in Laravel?

To use AJAX in Laravel, you need to import a jquery library in your view file to use ajax functions of jquery, which will be used to send and receive data using ajax from the server.


1 Answers

Most browsers can't send PUT methods and are restricted to just GET and POST.

Try changing the method to POST, but leave your _method element in the data array to spoof the request method.

like image 65
Martin Bean Avatar answered Oct 24 '22 13:10

Martin Bean