Categories
JavaScript Answers

How to append array to FormData and send via Ajax with JavaScript?

Spread the love

To append array to FormData and send via Ajax with JavaScript, we can use the spread operator.

For instance, we write

const formData = new FormData();
const arr = ["this", "is", "an", "array"];

for (const a of arr) {
  formData.append("arr[]", a);
}

console.log(...formData);

to loop through the arr array and call formData.append with the key and value of each FormData entry.

Then we use the spread operator to spread the formData key-value entries as arguments of console.log as arrays.

Conclusion

To append array to FormData and send via Ajax with JavaScript, we can use the spread operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to append array to FormData and send via Ajax with JavaScript?”

Hello,
Kindly assist with how to send an array with strings data to php via ajax
Message Body:

I have an array inside a JavaScript function
I need to send the array data to Php
How could i achieve this
hanks
David

Try using fetch to make a post request.

And then get the value on PHP side from $_POST.

Leave a Reply

Your email address will not be published.