Explain Codes LogoExplain Codes Logo

Appending Array to FormData and Sending via AJAX

javascript
form-data
ajax
javascript-utility-function
Nikita BarsukovbyNikita BarsukovยทJan 29, 2025
โšกTLDR

For quick tasks, you can encode your array as a JSON string using JSON.stringify() and then append it to FormData using .append(). Upon receiving the data, you can decode it using JSON.parse().

let formData = new FormData(); formData.append('myArray', JSON.stringify([1, 2, 3])); // roll your array into a JSON $.ajax({ url: 'server.php', // server side, brace yourself type: 'POST', data: formData, contentType: false, processData: false, success: console.log, // "Hurray! It worked! ๐ŸŽ‰" error: console.error // "Oops! Houston, we have a problem! ๐Ÿš€" });

Going a little deeper: Dealing with complex array solutions

Achieving complex structure preservation

Working with complex structures like nested arrays or objects? You need to recurse through these to maintain their structure when appending to FormData. Writing a utility function for this can be a time saver and a headache reducer.

Handling multidimensional arrays with care

When you have to work with multidimensional arrays, remember to iterate through each level to convert them correctly into a format that FormData can handle, preserving the structure on the server side.

Peek into your FormData

Before sending, you should give your FormData a quick health check to verify the correct structure using a simple console.log().

for (let [key, value] of formData) { console.log(key, value); // Doctor: "Let's see what we got here..." }

Baby, it's JSON outside

Transforming arrays into JSON strings isn't only for the cool kids; it provides the added benefit of structural preservation. json_decode() it on the PHP side, and your array is back again, in all its glory.

Leaving out the big guys

Filter out File objects when you're manually iterating and appending elements to the FormData. File objects like their space and should be appended separately.

Append: The secret to handling arrays and files

Attempting to append a whole array to FormData will give you a toString-ed version. To maintain the array structure, shout "one at a time" and append each individual element.

Working your way around stringent type checks

For projects growing like cabbage, using TypeScript might help. It's like having a shepherd that diligently cares about type-checking and helps keep your code more organized.

File handling: Doing it right

If you're sending files using FormData, they should be appended directly using formData.append('file', myFile). This appends the complete file object, which is just what you want for server-side processing.

The Explode: Dynamite on the server-side

Sometimes, the data string sent from JavaScript may need to be deserialized in PHP using explode(). Consider this method if the string is serialized in a non-standard way. Nuclear physicists and PHP developers, both use explode.