XMLHttpRequest to Post HTML Form

The POST string format is the following:

name=value&name2=value2&name3=value3

So you have to grab all names, their values and put them into that format.
You can either iterate all input elements or get specific ones by calling document.getElementById().

Warning: You have to use encodeURIComponent() for all names and especially for the values so that possible & contained in the strings do not break the format.

Example:

var input = document.getElementById("my-input-id");
var inputData = encodeURIComponent(input.value);

request.send("action=dosomething&" + input.name + "=" + inputData);

Another far simpler option would be to use FormData objects. Such an object can hold name and value pairs.

Luckily, we can construct a FormData object from an existing form and we can send it it directly to XMLHttpRequest‘s method send():

var formData = new FormData( document.getElementById("my-form-id") );
xhr.send(formData);

Leave a Comment