ajaxlaravelhttp-deletehttp-put

Laravel AJAX PUT & DELETE


On my development machine, everything works fine in regards to POST, PUT, DELETE, GET.

For example:

POST https://example.com/laravel/project (will create a new project - with data coming in from ajax)
PUT https://example.com/laravel/project/1 (will update the content of project with ID 1)
DELETE https://example.com/laravel/project/1 (will delete the project with ID 1)

However, I moved my project to production (a different server) and now

POST https://example.com/laravel/project (will create a new project as expected)
PUT https://example.com/laravel/project/1 (will not **update** project 1)
DELETE https://example.com/laravel/project/1 (will **not** delete project 1)

I have checked chrome's network tab, and I can see the cookies being present and the data that is coming in from the ajax call (for example, the fields that are updated/modified).

Also, I am getting a status 200 so there aren't any issues on webserver from what I understand too.

Examples of my ajax calls below - they are in $.ajax and have success and fail functions. just showing the important bits :)

type: 'POST',
url: '/laravel/project',
data: {
    '_token': $('input[name=_token]').val(),
    'project_name': $('#project_name_add').val(),
    'category': $('#category_add').val()
}

type: 'PUT',
url: '/laravel/project/' + id,
data: {
    '_token': $('input[name=_token]').val(),
    'project_name': $('#project_name_edit').val(),
    'category': $('#category_edit').val()
},

However, it is not actually updating or deleting anything.

Thanks for your help.


Solution

  • Try adding a hidden field to the form named _method. The feature is called method spoofing. https://laravel.com/docs/5.5/routing#form-method-spoofing

    <form action="/foo/bar" method="POST">
        <input type="hidden" name="_method" value="PUT">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
    </form>