Skip to content

JavaScript FormData append array

  • by

Using for loop you can append an array into a FormData object in JavaScript. For FormData.append() to work with an array, you need to JSON.stringify it.

let barArray = [{item: 'one'}, {item: 'two'}];

let data = FormData();

data.append('foo', JSON.stringify(barArray))

this.$inertia.post('/upload', data);

JavaScript FormData append array

Simple example code append an array to ‘FormData‘ in JavaScript?

<!DOCTYPE html>
<html>
<body>

  <script>
    var formData = new FormData;
    var array = ['1', '2'];
    for (var i = 0; i < array.length; i++) {
      formData.append('array_php_side[]', array[i]);
    }

    console.log("Form Data");
    for (let obj of formData) {
      console.log(obj);
    }
  </script>

</body>
</html>

Output:

JavaScript FormData append array

Or we can simply do like this.

formData = new FormData;
words = ["apple", "ball", "cat"]
words.forEach((item) => formData.append("words[]", item))

// verify the data
console.log(formData.getAll("words[]"))
//["apple", "ball", "cat"]

You can also send an array via FormData this way:

var formData = new FormData;
var arr = ['this', 'is', 'an', 'array'];

for (var i = 0; i < arr.length; i++) {
  formData.append('arr[]', arr[i]);
}

console.log(...formData);

Do comment if you have any doubts or suggestions on this Js FormData topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.