---
title: "What is the FormData API in JavaScript, and how do you use it to send form data via an AJAX request?"  
description: "The FormData API in JavaScript provides a way to easily construct a set of key/value pairs representing form fields and their values."  
author: "Ravi Vishwakarma"  
published: 2024-06-18  
updated: 2024-06-18  
canonical: https://www.mindstick.com/blog/304381/what-is-the-formdata-api-in-javascript-and-how-do-you-use-it-to-send-form-data-via-an-ajax-request  
category: "javascript"  
tags: ["web development", "javascript", "api(s)", "web api", "front-end development"]  
reading_time: 4 minutes  

---

# What is the FormData API in JavaScript, and how do you use it to send form data via an AJAX request?

The `FormData` API in JavaScript provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be sent using the `XMLHttpRequest` or `fetch` API. This is particularly useful for sending form data via [AJAX requests](https://www.mindstick.com/forum/157895/what-is-the-difference-between-synchronous-and-asynchronous-ajax-requests-in-mvc) without needing to manually serialize the form data.

#### Creating and Using `FormData`

To use the `FormData` API, you typically follow these steps:

1. **Create a FormData object**: You can create it from a form element or manually.
2. **Append data**: Add key/value pairs to the `FormData` object.
3. **Send data via AJAX**: Use `XMLHttpRequest` or `fetch` to send the `FormData` object.

#### Example: Using `FormData` with `fetch`

## HTML Form

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>JavaScript Ajax Demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style type="text/css">
    	.todo-item{
    		display: flex;
    	}
    	.todo-item.completed .todo-item-title{
    		text-decoration: line-through;
    	}
    </style>
  </head>
  <body>
    <div class="container mt-4">
    		<div>
    			<div class="d-flex justify-content-between">
    				<h1>Ajax Data</h1>
    			</div>
    			<hr/>
    		</div>
    		<div>
    			<!-- Add new todo data  -->
    			<div class="mb-3">
    				<form id="myForm">
    					<input type="hidden" name="userId" id="userId" value="1" />
    					<input type="hidden" name="id" id="id" value="0" />
    					<input type="hidden" name="completed" id="completed" value="false">
    					<div class="d-flex">
    						<input type="text" name="title" id="title" placeholder="Add a task" class="form-control" required />
    						<button type="submit" class="btn btn-primary ms-3">Add</button>
    					</div>
    				</form>
    				<hr/>
    			</div>
    			<!-- Show All todos -->
    			<div class="row g-3 todo-list" id="dynamic-area">
    			</div>
    		</div>
    </div>
  </body>
  <script src="JavaScript-ajax.js"></script>
</html>
```

JavaScript for Handling Form Submission (`JavaScript-ajax.js`)

```javascript
document.addEventListener('DOMContentLoaded', function() {

var responseData = [];

    // Load data from REST APIs
    fetch('https://jsonplaceholder.typicode.com/todos', {
        method: 'GET'
    })
    .then(response => response.json())
    .then(data => {
        //console.log('Success:', data);
        BindDatainHtmlPage(data);
        responseData = data;
    })
    .catch(error => {
        console.error('Error:', error);
    });

    function BindDatainHtmlPage(data){
        // Using querySelectorAll (returns a static NodeList)
        const elementsToRemove = document.querySelectorAll('.todo-item');
        elementsToRemove.forEach(element => element.remove());

        const area = document.getElementById('dynamic-area');
        for(item of data){
            var html = `<div class="todo-item ${ item.completed ? 'completed' : ''} ">
                        <div class="d-flex w-100 py-2 border-bottom" data-user-id="${item.userId}" data-post-id="${item.id}">
                            <span class="todo-icon mx-2 my-auto">
                                <i class="bi ${ item.completed ? ' bi-check-circle-fill text-success' : ' bi-circle'}"></i>
                            </span>
                            <p class="todo-item-title m-0 w-100 ">${item.title}</p>
                        </div>
                    </div>`;
            area.insertAdjacentHTML('afterbegin', html);
        }

    }

    const form = document.getElementById('myForm');
    form.addEventListener('submit', function(event) {
        event.preventDefault(); // Prevent the default form submission

        // Create a new FormData object from the form element
        const formData = new FormData(form);
        var newTodoItem = Object.fromEntries(formData.entries());

        // Send the form data using fetch
        fetch('https://jsonplaceholder.typicode.com/todos', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            //console.log('Success:', data);
            newTodoItem['id'] = parseInt(data.id);
            responseData.push(newTodoItem);
            BindDatainHtmlPage(responseData);
            form.reset();
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });
});
```

![What is the FormData API in JavaScript, and how do you use it to send form data via an AJAX request?](https://www.mindstick.com/blogs/a9581e3a-341f-4f19-bd74-c7253da0b6f7/images/a30fca9a-5c7b-4655-b996-f5f14393c4eb.png)

### Explanation

**HTML Form**:

- The form (`#myForm`) includes input fields for the title, id, userid, and a [submit button](https://www.mindstick.com/forum/130/its-possible-without-submit-button).

**JavaScript for Handling Form Submission**:

- An [event listener](https://www.mindstick.com/interview/529/how-to-remove-the-event-listener) is added to the form to handle the `submit` event.
- `event.preventDefault()` prevents the default form submission behavior, allowing you to handle it with JavaScript.
- A new `FormData` object is created from the form element, automatically capturing the form fields and their values.
- The `FormData` object can be inspected using a `for...of` loop, which iterates over its entries (key/value pairs).
- The `fetch` API is used to send the form data to a server endpoint.

   - `method: 'POST'` specifies the HTTP method.
   - `body: formData` sets the [request body](https://www.mindstick.com/forum/159965/how-can-you-read-data-from-the-request-body-in-an-express-js-application) to the `FormData` object.

- The response is handled with `.then()` for a successful request and `.catch()` for errors.

### Benefits of Using `FormData`

- **Simplifies Data Handling**: Automatically captures form fields and their values, including files (for [file uploads](https://www.mindstick.com/interview/34129/how-do-you-implement-file-chunking-for-large-file-uploads)).
- **Flexible**: Can be used with `XMLHttpRequest` and `fetch`.
- **Supports Various Data Types**: Easily handles different types of input fields, including text, files, and more.
- **Readable Code**: [Makes your](https://www.mindstick.com/blog/11381/what-makes-your-business-better) AJAX requests cleaner and easier to understand.

Using the `FormData` API is a powerful way to manage and submit form data via AJAX in modern [web applications](https://www.mindstick.com/blog/11464/improve-your-understanding-of-web-applications), streamlining the process of collecting and sending user input to the server.

## Read also,

[How can you perform client-side form validation in JavaScript?](https://www.mindstick.com/blog/304377/how-can-you-perform-client-side-form-validation-in-javascript)

[How can you dynamically add and remove form fields using JavaScript?](https://www.mindstick.com/blog/304378/how-can-you-dynamically-add-and-remove-form-fields-using-javascript)

[Describe how to implement a stack and a queue in JavaScript using arrays](https://www.mindstick.com/blog/304376/describe-how-to-implement-a-stack-and-a-queue-in-javascript-using-arrays)

---

Original Source: https://www.mindstick.com/blog/304381/what-is-the-formdata-api-in-javascript-and-how-do-you-use-it-to-send-form-data-via-an-ajax-request

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
