Javascript formdata to string

How to serialize form data with vanilla JS

Historically, getting data from a form into a format you could send to an API was a bit difficult, but modern techniques make it a lot easier.

The FormData object

The FormData object provides an easy way to serialize form fields into key/value pairs.

You can use the new FormData() constructor to create a new FormData object, passing in the form to serialize as an argument. Form fields must have a name attribute to be included object. Otherwise, they’re skipped. The id property doesn’t count.

For example, if you have a form that looked like this…

form id="post"> label for="title">Titlelabel> input type="text" name="title" id="title" value="Go to the beach"> label for="body">Bodylabel> textarea id="body" name="body">Soak up the sun and swim in the ocean.textarea> input type="hidden" name="userId" value="1"> button>Submitbutton> form>

You would serialize it like this…

// Get the form let form = document.querySelector('#post'); // Get all field data from the form // returns a FormData object let data = new FormData(form); 

Looping through FormData

The FormData object is an iterable, which means you can loop through it using a for. of loop (you’ll notice that a trend with many of the newer JS methods).

Each entry in the loop is an array of key/value pairs.

// logs. // ["title", "Go to the beach"] // ["body", "Soak up the sun and swim in the ocean."] // ["userId", "1"] for (let entry of data)  console.log(entry); > 

Because the entry values are arrays, you can also use array destructuring to assign the key and value to their own variables within the for. of loop.

// logs "title", "Go to the beach", etc. for (let [key, value] of data)  console.log(key); console.log(value); > 

Adding, updating, and removing items from a FormData object

The FormData object has several methods that you can use to add, remove, and update items.

Use the FormData.set() method to replace an existing entry, or add a new one if an entry with that key doesn’t exist. Pass in the key and value as arguments.

// Updates the userId field with a new value data.set('userId', '3'); // Creates a new key, "date", with a value of "4" data.set('date', 'July 4'); 

Use the FormData.append() method to add a new entry, passing in the key and value as arguments. If an item with that key already exists, another one is added and the existing one is unaffected.

// Add a second "body" key to the data FormData object data.append('body', 'Eat ice cream'); 

Use the FormData.delete() method to delete an entry, passing in the key as an argument. If more than one item with that key exist, all of them are deleted.

// Delete items with the "body" key data.delete('body'); 

How to convert a FormData object into an object or query string

The FormData object can be submitted as-is to some endpoints with a content-type header of multipart/form-data , not not all APIs support that.

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.

// Get the form let form = document.querySelector('#post'); // Get all field data from the form let data = new FormData(form); // Convert to a query string let queryString = new URLSearchParams(data).toString(); 

To serialize a FormData object into a plain object, we need to loop through each entry with a for. of loop and add it to an object.

let obj = <>; for (let [key, value] of data)  obj[key] = value; > 

But, if there’s more one form field with the same name, the original value will get overwritten. To account for this, we need to check if the key already exists in the obj . If it does, we want to convert it to an array and Array.push() the new value into it.

let obj = <>; for (let [key, value] of data)  if (obj[key] !== undefined)  if (!Array.isArray(obj[key]))  obj[key] = [obj[key]]; > obj[key].push(value); > else  obj[key] = value; > > 

Here’s a helper function you can use to convert a FormData object into a plain object. Pass in the FormData object as an argument.

function serialize (data)  let obj = <>; for (let [key, value] of data)  if (obj[key] !== undefined)  if (!Array.isArray(obj[key]))  obj[key] = [obj[key]]; > obj[key].push(value); > else  obj[key] = value; > > return obj; > 

And here’s how you would use it.

// Get the form let form = document.querySelector('#post'); // Get all field data from the form let data = new FormData(form); // Convert to an object let formObj = serialize(data); 

Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.

Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.

Источник

How to serialize form data to string without jquery or other libraries in javascript?

In JavaScript, serializing form data to a string is a common task when working with form submissions. This can be done without using any libraries, such as jQuery, and can be accomplished through a few different methods. Below are some methods to achieve form data serialization in pure JavaScript:

Method 1: FormData Object

To serialize form data to string using the FormData object in JavaScript, you can follow these steps:

const form = document.querySelector('form'); const formData = new FormData(form);
  1. Loop through the FormData object using the FormData.entries() method, which returns an iterator of all key/value pairs contained in the form data.
for (const [name, value] of formData.entries())  data[name] = value; >
  1. Convert the form data object to a query string using the URLSearchParams object, which provides a convenient way to create URL encoded strings.
const params = new URLSearchParams(data).toString();

Here is the complete code example:

const form = document.querySelector('form'); const formData = new FormData(form); const data = >; for (const [name, value] of formData.entries())  data[name] = value; > const params = new URLSearchParams(data).toString();

This code will serialize the form data to a URL encoded string, which can be sent to the server using an AJAX request or appended to the URL as query parameters.

Method 2: Using the Form Elements Collection

To serialize form data to string without jQuery or other libraries, you can use the Form Elements Collection. The following steps will demonstrate how to do this:

const form = document.getElementById('myForm'); // or const form = document.forms['myForm'];
for (let i = 0; i  form.elements.length; i++)  const element = form.elements[i]; if (element.name)  formData.push(`$element.name>=$encodeURIComponent(element.value)>`); > >
const serializedData = formData.join('&');
const form = document.getElementById('myForm'); const formData = []; for (let i = 0; i  form.elements.length; i++)  const element = form.elements[i]; if (element.name)  formData.push(`$element.name>=$encodeURIComponent(element.value)>`); > > const serializedData = formData.join('&');

This will serialize the form data to a string without using jQuery or other libraries.

Method 3: Serializing Manually

To serialize form data to string without using jQuery or other libraries, you can use the «Serializing Manually» method. Here’s how to do it:

let form = document.getElementById("myForm");
let data = ""; for (let i = 0; i  form.elements.length; i++)  let element = form.elements[i]; >
if (element.type !== "submit")  data += element.name + " token operator">+ encodeURIComponent(element.value) + "&"; >
data = data.substring(0, data.length - 1);
let form = document.getElementById("myForm"); let data = ""; for (let i = 0; i  form.elements.length; i++)  let element = form.elements[i]; if (element.type !== "submit")  data += element.name + " token operator">+ encodeURIComponent(element.value) + "&"; > > data = data.substring(0, data.length - 1);

This code will serialize all the form data into a string that can be sent to the server using an AJAX request or appended to a URL as query parameters.

Источник

How to Convert HTML Form Data to a JSON String in JavaScript?

Using JavaScript, you can choose different ways to convert HTML form values to a JSON string depending on the following:

Form Without Elements That Allow Multiple Selections

If your HTML form does not have elements that allow multiple selections (such as , checkboxes that have the same name , etc.), then you can simply do the following:

  1. Use the FormData API to access form data;
  2. Store form data (as key/value pairs) in an object;
  3. Convert form data object to a JSON string using the JSON.stringify() method.

For example, suppose you have the following HTML form:

You can access the submitted data from this HTML form and convert it to a JSON string in the following way:

The Object.fromEntries() was introduced in ES10. Therefore, to support earlier versions of ES, you could simply loop over the form data instead, for example, by using the FormData.entries() method, like so:

Form With Elements That Allow Multiple Selections

If your HTML form does have elements that allow multiple selections (such as , checkboxes that have the same name , etc.), then you can do the following:

  1. Use the FormData API to access form data;
  2. Store form data (as key/value pairs) in an object — if an element has multiple values, store an array of all the values. Otherwise, store the single value;
  3. Convert form data object to a JSON string using the JSON.stringify() method.

For example, suppose you have the following HTML form that has a multi-select and checkboxes with the same name attribute:

 
Hotel Apartments

You can access the submitted data from this HTML form and convert it to a JSON string in the following way:

// ES10+ const form = document.getElementById('myForm'); function formDataToObject(formData) < const normalizeValues = (values) =>(values.length > 1) ? values : values[0]; const formElemKeys = Array.from(formData.keys()); return Object.fromEntries( formElemKeys.map(key => Javascript formdata to string) ); > form.addEventListener('submit', function (event) < event.preventDefault(); // 1: get form data const formData = new FormData(form); // 2: store form data in object const jsonObject = formDataToObject(formData); // 3: convert form data object to a JSON string const jsonString = JSON.stringify(jsonObject); console.log(jsonString); // '' >);

The Object.fromEntries() was introduced in ES10. Therefore, to support earlier versions of ES, you could simply loop over the form data instead, for example, by using the FormData.entries() method, like so:

// ES5+ const form = document.getElementById('myForm'); function formDataToObject(formData) < const normalizeValues = (values) =>(values.length > 1) ? values : values[0]; const object = <>; for (const Javascript formdata to string of formData.entries()) < objectJavascript formdata to string = normalizeValues(formData.getAll(key)); >return object; >; form.addEventListener('submit', function (event) < event.preventDefault(); // 1: get form data const formData = new FormData(form); // 2: store form data in object const jsonObject = formDataToObject(formData); // 3: convert form data object to a JSON string const jsonString = JSON.stringify(jsonObject); console.log(jsonString); // '' >);

In either of the examples, the formDataToObject() function processes each form element and returns either a single value or an array of values, depending on whether the element has multiple values or not. This value is then added to its corresponding form element key in the resulting object.

Hope you found this post useful. It was published 22 Feb, 2023 . Please show your love and support by sharing this post.

Источник

Читайте также:  Buffer reading in java
Оцените статью