0

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

1

2 Answers 2

2
// 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
        )

)
Sign up to request clarification or add additional context in comments.

4 Comments

I am getting this error: TypeError: Argument 1 ('form') to the FormData constructor must be an instance of HTMLFormElement
I see that this in your context should be HTMLFormElement, so try using new FormData(this), not new FormData(form)
I fixed it like this: var form = $(this); Object.fromEntries(new FormData((form)[0]))
Or just var form = this; and Object.fromEntries(new FormData(form)). I have updated answer.
1

You're over-engineering your Javascript.

In this line:

data: {data:form.serialize()};

you're creating an object with data as a key and your serialized data as its value. When you pass that to jQuery for an AJAX call it passes that in that form. Hence you're finding your serialize string in $_POST['data'] and you have to unpack it.

You should send your serialised data to jQuery without packing it in an object:

data: form.serialize()};

jQuery will recognise that and send the daya with the correct keys so that you can read it directly in $_POST['firstname'], $_POST['lastname'], etc.

2 Comments

I am passing other data as well.
I answered the question you asked. If there's more to it then you should have included that in your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.