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

vincej's avatar
Level 15

Need some advice on saving a Ajax form data into L5

I'm making a mistake somewhere but I can't see it. Essentially my Ajax function works. But I can't get it into my controller for saving into my DB. What am I doing wrong ?

Many Thanks !

$("#editsubmit").click(function () {
            event.preventDefault();
   
                var formData = $("form").serialize();
    
                $.ajax({
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    type: "POST",
                    url: 'save_edit',    
                    dataType: 'json',
                    data: formData,
                    success: function () {

                        console.log(formData);   // GETTING A RESULT HERE. 

                        localStorage['alert'] = 'true';
                        location.href = "http://auburntree/open_quotes"
                    },
                    error: function () {
                        alert('there has been a system level error - please contact support')
                    }
                });
            
        });

Controller ( Abreviated) :

    public function save_quote_edited(Request $request){

           $newQuotation = new Quotation();
            $newQuotation->discount = $request->get('discount');
            $newQuotation->discount_value = round($request->get('discountvalue_hidden',2)); 
            $newQuotation->netofdiscount = $request->get('netofdiscount_hidden');
            $newQuotation->gst = $request->get('gst_hidden');
            $newQuotation->total =  round($request->get('final_total_hidden',2));                                  
            $newQuotation->save();
}

0 likes
21 replies
jlrdw's avatar

datatype doesn't need to be json for a post, just post it through the jquery ajax normal, json is more for getting a response back to a jquery request. Here a laravel controller method is taking care of business.

vincej's avatar
Level 15

@jlrdw Thanks for helping out. As suggested, I removed the datatype:json and It's still not woking. Any more ideas ?

cheers !

jlrdw's avatar

I'd completely get it working without Ajax then once it is all checked out then use ajax. Oh, double check your Ajax code.

DarkRoast's avatar

Open your inspector > network tab and send the request again. You should be able to see what error the server is returning (so long as your not running it in production).

Snapey's avatar

in the success section you comment "getting a result here"... What do you get?

vincej's avatar
Level 15

@snapey my consol log shows the serialized values of the form. So I am assuming my Ajax is good.

ccarver's avatar

Hi,

I wouldn't bind to a click event, instead to the form id and listen for the submit event. (But you can do it either way)

So it would be like

<form id='myForm'> bla bla </form>

The JS

$('#myForm').submit(function(event) {
    prevent default, do stuff
});

or you can still attach to a click event

$('#editsubmit').click(function(event) {
    $('#myForm').submit();
});

The documentation is here https://api.jquery.com/submit/

Also, I would recommend the amazing library axios https://github.com/mzabriskie/axios

What do you get when you dd(request()->all()); ?

vincej's avatar
Level 15

@ccarver thanks for your help. to answer your question, when I use dd(request()->all()); I get nothing.

Snapey's avatar

but the success callback is the reply from the server, but you are not logging that, you are logging what you already sent.

Concentrate on the browser to start with.

Inspect the page

switch to the network tab

submit the form

see the network call to the server. Did it go to the route you expected? was the form data attached? what was the reply from the server.

you can see all this by clicking on the request in the left panel and seeing headers and response on the right.

jlrdw's avatar

Is this correct

url: 'save_edit',

Sometimes a slash is needed but make sure the path is correctly resolved.

Snapey's avatar

@jlrdw is probably on the money. I was trying to encourage you to learn how to debug these issues rather just change something, or worse just abandon and switch to a different method, where if you don't understand what is happening you will have the same issue.

If, for instance, the current page is example.com/quotes/edit then sending the ajax to 'save_edit' will actually go to example.com/quotes/edit/save-edit which is possibly not what you want and will result in the server returning a not found error.

1 like
jlrdw's avatar

@vincej I usually don't post with ajax, I usually use "get" to maybe return some non-critical data. But I played with it today, and this works, note I only did a couple fields for experiment:

$(function () {

                            $("#postjq").click(function (event)
                            {
                                event.preventDefault();
                                var $post = {};
                                $post.petid = $('#petid').val();
                                $post.species = $('#species').val();
                                $post._token = document.getElementsByName("_token")[0].value
                                $.ajax({
                                    url: '<?php echo "petupdate"; ?>',
                                    type: 'POST',
                                    data: $post,
                                    cache: false,
                                    success: function (data) {
                                        return data;
                                    },
                                    error: function () {
                                        alert('error handing here');
                                    }
                                });

                            });
});

Used getElementsByName for _token, because the helper that generates the token puts a name but no id.

Snapey's avatar

@jlrdw Its not safe to ignore csrf. I know you say non-critical, but next thing you know you have copied the method and used it for setting the user's profile.

This addition to your post array would give you the protection

$post._token = '{!! csrf_token() !!}';

Snapey's avatar

@jlrdw at the risk of hijacking Vince's thread, I can't follow why you are looking for the _token element. My approach inserts it directly into the javascript when the page is built in blade template. The time this does not work is when the javascript is a static file, in which case, in 5.3, Taylor provides both a meta data way to get the token, or javascript Window.Laravel variable.

I suppose if the form needed to work with JS disabled then you would still have the hidden token field, but that doesn't stop you directly accessing one of the others, e.g.;

'$post._token' = $('meta[name="csrf-token"]').attr('content');

jlrdw's avatar

@Snapey I always treat a form like it's going to be a regular posted form first without Ajax all the getElementsByName is doing is of course getting that piece of information just like the other pieces of information. I have not tried the meta yet I suppose it would work as well but either way you're passing the token as you are supposed to.

vincej's avatar
Level 15

@jlrdw @Snapey @ccarver @DarkRoast

I want to thank all four of you guys for taking the time out of your day to help people like me. Without you guys, people like me would probabaly give up. I'm not totally inexperienced. I've done about 18 months on Laravel, 2 years on Codeigniter and about 18 months on pure php. So about 5 years altogether. Still I make mistakes.

Ok - so it looks like I have found the problem. It was never with the AJAX, but rather within the Abreviated controller, which of course you guys could not wholly see. I follwed snapey's advice and checked the XHR and saw the data going out. But I kept getting a '500' error which is nearly always a DB or a controller error. So I stripped my controller down to 2 values to save and bingo, success.

So now I will rebuild the controller untill it fails and I find the error.

Yes, I know I should install Xdebug in my PHPStorm. I have tried now 2 times and failed each time to get it to work. It's either me of the terrible docs. Time is always against me and so spending another 2 hours fighting with Storm fills me with dread.

I have to use Ajax to submit a form on a click for the reason that my form contains js generated rows and a simple html submit doesn't work. ccarver - I wil try your suggesting of using a submit.

Many thanks to all !!!

kidstell's avatar

i was gonna say always let your success function take the data argument

success:function(data){
    console.log(data)
},
error:function(data){
    console.log(data)
}, //...

i want to also advice you do some dd() in the controller, this requires some fine tuning until you are sure that the controller is being called, you could even apply conditional statements to every action in the controller function to be sure which one returns boolean instead of an object.

lastly , on my watch, be sure you have a route actually pointing the post request to the controller function

nolros's avatar

@vincej the data is coming through as a string because your serializing the data i.e. you are not passing through JSON You can grab the strin using PHP server commands encode to JSON, but you don't need to do that. ->get() is looking for JSON and not finding it.

So I suggest try just passing the JSON data versus serializing i.e. pass as JS object or array.

var formData = $("form");

1 like
vincej's avatar
Level 15

@nolros Thanks - I always appreciate your help. I will try to remember that.

Please or to participate in this conversation.