-2

I have a form which I get the data from with new FormData(form). I'm having trouble getting my HTML arrays to properly pass over to PHP. I'm using vanilla JS and for example, in jQuery, using serializeArray() would have serialized my HTML into something PHP understands. But now with JSON.stringify, it seems to ignore HTML arrays completely and I get this:

{"postData[0][val]":"1"} passed over to PHP, where I would expect

{"postData": ["0": ["val": "1"]]}

My HTML:

<select name="postData[0][val]">
    <option value="1">nothing</option>
    <option value="2">boy</option>
    <option value="3">girl</option>
</select>

<input name="postData[0][val2]" type='number'>

My Javascript:

const formData = new FormData(form).entries();
let postData = {};

for (var pair of formData) {
    postData[pair[0]] = pair[1];
}

fetch(`${base}events/play/${event_id}`, {method: 'post', body: JSON.stringify(postData)})

I am properly reading the input in PHP.

Vael Victus
  • 3,966
  • 7
  • 34
  • 55
  • 1
    `postData[0][val]` is a string and is the name of the `select` field. So `{"postData[0][val]":"1"}` is indeed what I would expect from your code. – jrswgtr Feb 28 '20 at 12:59
  • Also there is no such thing as HTML arrays. HTML is just a markup language and doesn't know about data types – jrswgtr Feb 28 '20 at 13:02
  • Does this help you: https://stackoverflow.com/questions/41431322/how-to-convert-formdatahtml5-object-to-json – twain Feb 28 '20 at 13:03
  • I didn't know another way to express what I need to do here. Because indeed HTML understands them as a string, but `serializeArray()` from jQuery was able to pass it along so that PHP understood it as an array. I'm looking for similar (and hopefully standard) functionality here. – Vael Victus Feb 28 '20 at 13:03
  • I think there might be something there that does, @twain. It looks like a solution to this may not come out of the box in javascript. – Vael Victus Feb 28 '20 at 13:13

1 Answers1

0

I had mistakenly believed that I had to JSON.stringify() all fetch POST requests to PHP; this was not the case. From the docs:

Both requests and responses may contain body data. A body is an instance of any of the following types: ArrayBuffer, ArrayBufferView, Blob/File, string, URLSearchParams, FormData

I was able to reduce it down to only these two lines:

const postData = new FormData(form);
fetch(`${base}events/play/${event_id}`, {method: 'post', body: postData})

Now it's sent in as $_POST, not file://input. Not my finest moment, but I did find this Q&A to be helpful for those who need help with something similar.

Vael Victus
  • 3,966
  • 7
  • 34
  • 55