Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 391
kleinfreund Avatar asked Mar 23 '17 15:03

kleinfreund


People also ask

How do I create a query string?

An easy way to build a query string in Javascript is to use a URLSearchParams object: var query = new URLSearchParams(); query. append("KEY", "VALUE");

How do I serialize FormData?

To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.

How do you get data from forms?

The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.

What is post query string?

Post uses the message body to send the information back to the server, as opposed to Get, which uses the query string (everything after the question mark). It is possible to send both a Get query string and a Post message body in the same request, but that can get a bit confusing so is best avoided.


1 Answers

You could use URLSearchParams

const queryString = new URLSearchParams(new FormData(myForm)).toString() 
like image 185
Hans Avatar answered Oct 14 '22 21:10

Hans