Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

motazdev's avatar

Laravel 8 Ajax Update Record

Hey Guys i was trying to update order status with ajax & Bootstrap Modal. But I got that error after submitting to update.

I got this code from internet because i'm not good at ajax.. and not professional in Laravel tbh

Uncaught TypeError: Illegal invocation

 
    
        function editStatus(e) {
            var id  = $(e) .data("id");
            var status  = $("#order_"+id+" td:nth-child(2)") .html();
            $("#id") .val(id);
            $("#status") .val(status);
            $('#orderEditModal') .modal('show');
        }
    
        function updateStatus() {
            var status = $('#status') .val();
            var id = $('#id') .val();
            let _url     = `/admin/orders/${id}`;
            let _token   = $('meta[name="csrf-token"]').attr('content');
    
            $.ajax({
                url: _url,
                type: "PUT",
                data: {
                    status: status,
                    user_id: user_id,
                    _token: _token
                },
                success: function(data) {
                        status = data
                        $("#order_"+id+" td:nth-child(2)") .html(status .status);
                        $('#id').val('');
                        $('#EditModal').modal('hide');
                }
            });
        }
    

There is a strange spaces that's because i cant put any link

0 likes
20 replies
jlrdw's avatar

Have you done the spoof for the put method.

motazdev's avatar

okay i added that and the error still exist

jlrdw's avatar

Has to be passed also in ajax.

var _method = document.getElementsByName("_method")[0].value;

Put works, just pass the correct variables. I use put all the time.

motazdev's avatar

okay i added that

            var _method = document .getElementsByName("_method")[0] .value;


            $.ajax({
                url: _url,
                type: "PUT",
                data: {
                    status: status,
                    user_id: user_id,
                    _token: _token,
                    _method:_method
                },

and also the same error appear..

motazdev's avatar

here is the code in the controller

    public function update(Order $order, Request $request)
    {
        $request->validate([
            'status' => 'required',
            'user_id'
            ]);
            

        $order->status = $request->status;
        $order->user_id = $request->user_id;
        $order->save();
        return Response::json($order);
    }

motazdev's avatar

i removed all my ajax code and replace that javascript.

and gives me that

Uncaught TypeError: Cannot read property 'preventDefault' of undefined
submitPost @ orders : 251
onclick @ orders:184
orders : 257 PUT ht tp : // localhost/admin/orders net : : ERR_CONNECTION_REFUSED
submitPost @ orders:257
 Error: TypeError: Failed to fetch

sorry if you're busy but if i solved this error the project will be finished

motazdev's avatar

and here is the code


        document .getElementById('submitBtn') .addEventListener('click', submitPost);
    function submitPost(e) {
        e .preventDefault();
        const data = {
            id: document .getElementById('id') .value,
            status: document .getElementById('status') .value,
            _token: document .getElementsByName("_token")[0] .value,
            _method: document .getElementsByName("_method")[0] .value};
        fetch('h t tp : / /localhost/admin/orders', {
            method: 'PUT', // or 'POST'
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON .  stringify(data),
        })
                .then(function (response) {
                    if (response .status === 200) {
                        response . json() .then(function (data) {
                            //console .log(data . type, data . message)
                            var div = document . getElementById ('msg');
                            for (var key in data) {
                                div . innerHTML + = data[key];
                            }
                        })
                    }
                    if (response .status === 422) {
                        response .json() .then(function (data) {
                            //console .log(data .type, data .message)
                            var div = document .getElementById('msg');
                            for (var key in data) {
                                div .innerHTML += data[key];
                            }
                        })
                    }
                    if (response .status === 403 || response .status === 500) {
                        response .json() .then(function (data) {
                            var div = document .getElementById('msg');
                            div .innerHTML += "Not Authorized";

                        })
                    }

                })

                .catch((error) => {
                    console .error('Error:', error);
                    document .getElementById('msg') .innerHTML = "An error occured";
                });
    }
jlrdw's avatar

The fetch js example was just for learning, not an actual solution to fix tour code. You should (for now) fix the jquery code.

But if you want to try fetch, you have an extra space:

e .preventDefault();

change to

e.preventDefault();

Make sure you have a division with id of msg to display the messages. Again it was just an example of fetch js usage, you have to adapt to your code and use case.

I will try to get you an example of some working jquery code, may take a few minutes. But will only be an example.

1 like
motazdev's avatar

yes i understand that it's just an example but as i told you its my first time to use laravel with ajax or with JS. and thank you i appreciate that bro

jlrdw's avatar
jlrdw
Best Answer
Level 75

Here is a working jquery example, (just example):

    $(function () {
        $("#postjq").click(function (event)
        {
            event.preventDefault();
            var $post = {};
            $post.petid = $('#petid').val();
            $post.species = $('#species').val();
            $post.ocheck = ($("#ocheck").prop("checked") == true ? '1' : '0');
            $post._token = document.getElementsByName("_token")[0].value
            $post._method = document.getElementsByName("_method")[0].value
            
            $.ajax({
                url: '<?= DIR . "pet/petupdate" ?>',
                type: 'PUT',
                data: $post,
                cache: false,
                success: function (data) {
                    var message = "data updated";
                    alertWithoutNotice(message);
                    $('#msg').append('<div>' + data.success + '</div>');

                },
                error: function (data, ajaxOptions, thrownError) {
                    var status = data.status;
                    if (data.status === 422) {
                        $.each(data.responseJSON.errors, function (key, value) {
                            $('#msg').append('<div>' + value + '</div>');
                        });
                    }

                    if (status === 403 || status === 500) {
                        $('#msg').text("Not Auth");
                    }
                }
            });
        });


        function alertWithoutNotice(message) {
            setTimeout(function () {
                alert(message);
            }, 1000);
        }

    });

Note

I don't use json in this example, I use an array. But it works, you can adapt as needed and use json if you want.

I am moving to fetch js, that's why I gave you the other example.

1 like
motazdev's avatar

okay i think everthing is good but i got 404 error! i use laravel telescope and in the request payload gives me the right data

{
"id": "1",
"status": "completed",
"_token": "LT97sG7CtLwE5eN63orV0PvkO99Y7f7WzXmzrSGj",
"_method": "PUT"
}

so how to solve that 404 ? sorry again i know i should learn laravel first and ajax but i have to finish that project

jlrdw's avatar

Make sure you route and controller code is correct. And if you get it solved mark as solved.

404 is page not found, so check your url in ajax is correct also.

motazdev's avatar

okay don't worry. i solved that 404 but gives me 500 (Internal Server Error) what is the problem ?

jlrdw's avatar

Check laravel error log, and also use network tab to see what's going on. Log is under storage\logs\laravel.log

motazdev's avatar

sorry again. i checked the logs but i couldnt solve anything. but what i saw that after i submit and gives me Error 500. i reloaded the page and the record updated!! so the problem now that the change doesnt appear.. do you know anything to solve this ?

jlrdw's avatar

Maybe do some more searching, and some trial and error. Not knowing all your code it makes it hard to troubleshoot.

Are you returning a response json back to your ajax call:

return Response::json(['success' => 'all okay']);  use your custom message.

All I showed you works 100%, so double check your code, routes, controller, etc. You may need a little trial and error troubleshooting.

motazdev's avatar

okay bro thank you so much and i will give you the best answer

Please or to participate in this conversation.