javascriptxmlhttprequestform-data

Easier way to transform FormData into query string


I’m sending a POST request via XMLHttpRequest with data entered into an HTML form. The form without interference of JavaScript would submit its data encoded as application/x-www-form-urlencoded.

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

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('&'));

    // Prevent submitting the form via regular request
    event.preventDefault();
});

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


Solution

  • You could use URLSearchParams

    const queryString = new URLSearchParams(new FormData(myForm)).toString()