How to Serialize Form Data with Javascript

Serialization of form data means to create a string of URL encoded name-value pairs of the form data parameters. Each pair is separated by a & character.


While implementing AJAX requests, libraries such as jQuery handle serialization of form data by themselves. But when trying to do this with vanilla Javascript (using XHR), it becomes your responsibility to serialize the form data to be sent.

You can form a query string of encoded key/value pairs by appending parameters to a string, but somehow doing that seems like a waste of time. There are external libraries that do this — but using libraries for such small purposes is not very right.

The good news is that modern browsers have methods that can serialize form data natively. This happens with the URLSearchParams and FormData objects.

Serialiazing Form Data for a GET Request

For a GET request, you can get a url encoded query string by using the URLSearchParams object.

Multiple values for a single parameter can also be handled.

// new URLSearchParams object
var search_params = new URLSearchParams(); 

// append parameters
search_params.append('post', '12');
search_params.append('post', '15');
search_params.append('sort', 'desc');
search_params.append('contains', 'U A');

// query string
var query_string = search_params.toString();

// will output "post=12&post=15&sort=desc&contains=U+A"

// send form data in AJAX request
var xhr = new XMLHttpRequest();'GET', 'ajax.php');

Serialiazing Form Data for a POST Request

  • Simple POST request (no files uploaded)

    When no files are being uploaded, the Content-Type header of the POST request is usually application/x-www-form-urlencoded.

    The query string in this case is just like the query string of a GET request — each name-value pair separated by a & character.

    So you can use the URLSearchParams object in this case also (described above).

  • POST request with files uploaded

    When files are being uploaded, the Content-Type header of the POST request is multipart/form-data.

    In this case form data is separated by a specific boundary.

    The URLSearchParams object won't work in this case. You will need the FormData object here.

    // new FormData object
    var formdata = new FormData();
    // textual parameters
    formdata.append('post', '12');
    formdata.append('type', 'normal');
    // file to be uploaded
    // comes from a file input
    formdata.append('file', document.querySelector("#file").files[0]);
    // send form data in AJAX request
    var xhr = new XMLHttpRequest();'POST', 'ajax.php');

Useful Resources