Easier way to transform FormData into query string : <p>I’m sending a POST request via <code>XMLHttpRequest</code> with data entered into an HTML form. The form without interference of JavaScript would submit its data encoded as <code>application/x-www-form-urlencoded</code>.</p>

<p>With the XMLHttpRequest, I wanted to send the data with via the <code>FormData</code> API which does not work since it treats the data as if it were encoded as <code>multipart/form-data</code>. Therefor I need to write the data as a query string, properly escaped, into the send method of the <code>XMLHttpRequest</code>.</p>

<pre><code>addEntryForm.addEventListener('submit', function(event) {
    // Gather form data
    var formData = new FormData(this);
    // Array to store the stringified and encoded key-value-pairs.
    var parameters = []
    for (var pair of formData.entries()) {
        parameters.push(
            encodeURIComponent(pair[0]) + '=' +
            encodeURIComponent(pair[1])
        );
    }

    var httpRequest = new XMLHttpRequest();
    httpRequest.open(form.method, form.action);

    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.status === 200) {
                console.log('Successfully submitted the request');
            } else {
                console.log('Error while submitting the request');
            }
        }
    };

    httpRequest.send(parameters.join('&amp;'));

    // Prevent submitting the form via regular request
    event.preventDefault();
});
</code></pre>

<p>Now this whole thing with the <code>for ... of</code> loop, etc. seems a bit convoluted. Is there a simpler way to transform <code>FormData</code> into a query string? Or can I somehow send FormData with a different encoding?</p>
