Jump to content

Submitting forms with arrays as JSON


NotionCommotion

Recommended Posts

When submitting application/x-www-form-urlencoded data to PHP, using names such as roles[] does the trick.

<form id="addRecordForm">
    <input type="text" class="form-control" id="firstName" name="firstName" placeholder="John">
    <input type="text" class="form-control" id="lastName" name="lastName" placeholder="Doe">
    <input type="hidden" name="roles[]" value="ROLE_1">
    <input type="hidden" name="roles[]" value="ROLE_2">
</form>

However, I will be sending application/json;charset=UTF-8.  To get the data, I typically using the following, but it will not work with inputs with array data and will only include the second ROLE_2.

var data = Object.fromEntries(new FormData( form ));

I can come up with a hack (i.e. explicitly get the content from FormData before executing Object.fromEntries())  to meet my immediate needs, but would rather standardize on a better solution.  Any recommendations?

Link to comment
Share on other sites

My hack which I would rather not use.

    function formDataToObj(formData) {
        var o={};
        for (var [key, val] of formData.entries()) {
            if(key.slice(-2)==='[]') {
                key = key.substr(0, key.length-2);
                if (typeof o[key] === 'undefined') {
                    o[key] = [];
                }
                o[key].push(val);
            }
            else {
               o[key] = val; 
            }
        }
        return o;
    },

 

Link to comment
Share on other sites

Any particular reason you have to be sending JSON from this form? REST commonly uses JSON nowadays, sure, but that doesn't mean you can't also accept requests in other formats as long as the data decodes into the correct schema.

In an ideal web framework, the Content-Type of the input is not restricted. It can be whatever as long as the framework knows how to interpret it. That's why abstracting out $_POST is nice: PHP only handles a couple types, but a framework could read the Content-Type and decode the input appropriately.

Link to comment
Share on other sites

18 hours ago, requinix said:

Any particular reason you have to be sending JSON from this form?

No, and I should make it able to do so...  Eventually.  But I haven't implemented the other content types yet and wish to at least get one thing working first.  And while maybe I should always know the latest JS latest cool way for doing things, it annoys me sometimes having to learn them when I don't have time to do so.

Can you be more specific regarding my very non-abstract question? :)

Link to comment
Share on other sites

It's not as succinct as one could hope, but this should work.

let vals = [];
let fields = document.getElementsByName('roles[]');
for(let item of fields){
  vals.push(item.value);
}
console.log(JSON.stringify(vals));

I had thought the forEach() method would work, but had trouble with that, and of course the return is a NodeList instead of a true Array so using map() wouldn't work either.

Edited by maxxd
Link to comment
Share on other sites

10 hours ago, NotionCommotion said:

No, and I should make it able to do so...  Eventually.  But I haven't implemented the other content types yet and wish to at least get one thing working first.  And while maybe I should always know the latest JS latest cool way for doing things, it annoys me sometimes having to learn them when I don't have time to do so.

If you're already detecting application/json then it wouldn't be much more to handle urlencoded...

Do you need to support []s in other forms in the immediate future? If not then I'd probably go for maxxd's direct approach, even if it's just for this specific form.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.