0

So I am appending additional data to FormData:

 async submit(el, codes = null) {
        try {
            const formData = new FormData(el);

            if (codes) {
                for (let i = 0; i < codes.length; i++) {
                    formData.append('codes[]', codes[i]);
                }
            }

            const response = await http({
                method: el.method,
                url: el.action,
                data: formData,
            });
    }
}

But this is what I get:

[2021-09-01 08:56:57] local.INFO: array (
  'email' => '[email protected]',
  'password' => 'password',
  'codes' => 
  array (
    0 => '[object Object]',
  ),
)  

And how it should be:

[2021-09-01 09:00:18] local.INFO: array (
  'email' => '[email protected]',
  'password' => 'password',
  'codes' => 
  array (
    0 => 
    array (
      'code' => 'test2',
      'puk' => 'DH58LEJV',
    ),
  ),
)  

How should I fix this?

4

1 Answer 1

0

The append() function takes a key/value pair. So the value should be a string or number etc. In your case it looks like an object because object.toString() will return "[object Object]". So, maybe you should just stringify the object:

var codes = [{
  code: 'test1',
  puk: 'DH58LEJV'
}, {
  code: 'test2',
  puk: 'DH58LEJV'
}];

document.forms.form01.addEventListener('submit', e => {
  e.preventDefault();
  let formData = new FormData(e.target);
  codes.forEach(code => {
    formData.append('codes[]', JSON.stringify(code));
  });

  fetch(e.target.action, {
      method: e.target.method,
      body: formData
    })
    .then(res => res.text())
    .then(text => console.log(text));
});
<form name="form01" method="POST" action="data:text/plain;base64,dGVzdA==">
  <input type="text" name="email" value="[email protected]" />
  <input type="password" name="password" value="1234" />
  <button>Send</button>
</form>

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

Comments

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.