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

tony
  • 506
  • 2
  • 17
  • This should help you: [Convert form data to JavaScript object with jQuery](https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery) – id'7238 Feb 13 '21 at 01:38

2 Answers2

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
        )

)
id'7238
  • 2,428
  • 1
  • 3
  • 11
  • I am getting this error: TypeError: Argument 1 ('form') to the FormData constructor must be an instance of HTMLFormElement – tony Feb 13 '21 at 03:51
  • I see that `this` in your context should be HTMLFormElement, so try using `new FormData(this)`, not `new FormData(form)` – id'7238 Feb 13 '21 at 03:56
  • I fixed it like this: var form = $(this); Object.fromEntries(new FormData((form)[0])) – tony Feb 13 '21 at 04:03
  • 1
    Or just `var form = this;` and `Object.fromEntries(new FormData(form))`. I have updated answer. – id'7238 Feb 13 '21 at 04:04
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.