Sinres
7 months ago

400 Bad Request in method DELETE and PATCH

Posted 7 months ago by Sinres

Hello Guys!

I have a problem with delete and update records from DB by Ajax in Laravel project. Everything was fine until I moved the project to external hosting.

Method Get and Post they work correctly. When I change PATCH to POST record updated correctly but this isn't a solution to the problem.

In my localhost all working correctly ...

This is my code:

Update record

// Update ServiceList record
$(document).on('submit', '#formServiceEdit', function (e) {
    e.preventDefault();

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

    var form = $('#formServiceEdit');
    var formData = form.serialize();
    var url = form.attr('action');
    var state = $('#update').val();
    var type = 'PATCH';

    $.ajax({
        type: type,
        url: url,
        data: formData,
        success: function (data) {
            console.log(data);
            $('#list' + data.id).remove();
            $('#edit-service-request').modal('hide');
            pageAlertSuccess();
    },

        error: function (data) {
            console.log(data)
            pageAlertError();
            console.log("Error");
        },
    })
})

Delete record

// Delete service record 
$(document).on('click', '.btn-delete-service', function () {
    var value = $(this).data('id');
    var url = (window.location.href);
    url = url.split('/search')[0];
    url = url.split('?page')[0];
    url = (url + '/remove');
    console.log(value);
    if (confirm('You are sure?') == true) {
        $.ajax({
            type: 'delete',
            url: url,
            data: {
                "_method": 'POST',
                "id": value
            },
            success: function (data) {
                $('#list' + value).remove();
                $('#delete-service-request').modal('hide');

            },
            error: function () {
                console.log("Error")
            },
        })
    }
})

And my controller method:

public function update(Request $request)
    {

        if ($request->ajax()) {
            $serviceList = ServiceList::find($request->id);
            $serviceList->updated_by = Auth::id();
            $serviceList->update($request->except('user_id'));
            $serviceList->user;

            return Response($serviceList);
        }
    }
public function destroy(Request $request)
    {
        if ($request->ajax()) {
            $serviceList = ServiceList::destroy($request->id);
            return Response($serviceList);
        }
    }

Please sign in or create an account to participate in this conversation.