Skip to content
Advertisement

Submit form with Ajax in array format, not serialized?

I want to submit a form using Ajax but I want it to be in an array, not serialized.

var form = $(this);
data: {data:form.serialize()};

gives me this in my PHP:

firstname=John&lastname=Doe&phone=123123412345

and I have to run this code in PHP to get it into the format I want:

parse_str($_POST['data'], $data);

Just seems super unnecessary and I would like to remove that step. How can I just pass the form in an array format? Thanks

Advertisement

Answer

// var form = $(this);
var form = this;
data: {data: Object.fromEntries(new FormData(form))}

then you will get the $_POST variable like this:

Array
(
    [data] => Array
        (
            [firstname] => John
            [lastname] => Doe
            [phone] => 123123412345
        )

)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement