How To Get Form Data Using FormData Object In AJAX

In This article will learn how to get form data using FormData object and pass in ajax.

First of all, create a PHP file index.php and put the below HTML structure in the index.php file.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>How To Pass FormData In AJAX</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script type="text/javascript" src="js/custom.js"></script>
</head>
<body>
  <div class="container">
    <div class="card mt-5">
     <div class="card-header text-center">
      <h3>FORMDATA</h3>
      </div>
      <div class="card-body">
      <form method="post" class="row g-3" id="form" role="form" enctype="multipart/form-data">
        <div class="col-md-6">
          <label for="firstname" class="form-label">First Name</label>
          <input type="text" name="firstname" class="form-control" id="firstname">
        </div>
        <div class="col-md-6">
          <label for="lastname" class="form-label">Last Name</label>
          <input type="text" name="lastname" class="form-control" id="lastname">
        </div>
        <div class="col-md-6">
          <label for="email" class="form-label">Email</label>
          <input type="email" name="email" class="form-control" id="email">
        </div>
        <div class="col-md-6">
          <label for="password" class="col-sm-2 col-form-label">Password</label>
          <input type="password" name="password" class="form-control" id="password">
        </div>
        <div class="col-12">
          <label for="formFile" class="form-label">Choose File</label>
          <input class="form-control" name="file" type="file" id="formFile">
        </div>
        <div class="col-12">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="gridCheck" id="gridCheck">
            <label class="form-check-label" for="gridCheck">
            Check me out
            </label>
          </div>
        </div>
        <div class="col-12">
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
      </div>
    </div>
  </div>
</body>
</html>

Then, create a js folder and create a custom.js file in it.

Then put the below js in the custom.js file. (Notes: make sure the jquery file has been included in the main file index.php).

Then create a get_data.php with index.php for a string URL to which you want to submit or retrieve the data.

Here is define there are some methods of FormData.

Methods:

1. FormData.append():

Syntax:

formData.append(key, value);
formData.append(key, value, filename);

Parameters:

key: Add a field Names
value: Add a Field value
filename: this parameter is optional. added a filename. The default filename for the ‘Blob’ object is a blob. The default filename is the file’s filename.

Example:

//FormData.append() - For a ther data can added in a formdata object
   formdata.append('key', 'value');

2. FormData.entries():

These methods use to display pair of keys/values of the form data object.

Syntax:

formData.entries();

Example:

//FormData.entries() - For display a key/value of formdata object.
    for(var data of formdata.entries()) {
       console.log(data[0]+ ', '+ data[1]);
    }

3. FormData.delete():

These methods use to delete objects from form data.

Syntax:

formData.delete(keyname);

Parameters:

key name: add the name of the key you want to delete.

Example:

//FormData.delete() - For delete object form formdata
    formdata.delete('firstname');

4. FormData.get():

This method is used to get the first value of the associated key from the FormData object.

If we want an all value of key from the FormData object, we can use a getAll() method instead of get().

Syntax:

formData.get(keyname);

Parameters:

name: add the key to which value want to receive

Example:

//FormData.get() - For getting first values of the associated key name
    var getdata = formdata.get('lastname');
    console.log(getdata);

5. FormData.getAll():

This method is used to get all associated key values from the FormData object.

Syntax:

formData.getAll(keyname);

Parameters:

name: add the key to which value want to receive

Example:

//FormData.getAll() - For getting all values of the associated key name
    	formdata.append('lastname', 'value1');
    	formdata.append('lastname', 'value2');
    var getdata = formdata.getAll('lastname');
    console.log(getdata);

6. FormData.has():

This method is used to check FormData object contains a particular key.

If the FormData object contains a certain key, this method returns a boolean value.

Syntax:

formData.has(name);

Parameters:

name: add the key to which you want to test

Example:

//FormData.has() - Return a Boolean value of respected a key
    var keyhas = formdata.has('key');
    console.log(keyhas);

7. FormData.keys():

This method is used to return a key of respected value.

Syntax:

formData.keys();

Example:

//FormData.keys() - Display a key of respected value.
    for (var key of formdata.keys()) {
       console.log(key);
    }

8. FormData.set():

This method is used to set field data in formData.

Syntax:

formData.set(name, value);
formData.set(name, value, filename);

Parameters:

Name: add a filed name.

Value: add a field value.

Filename: This parameter is optional. added a filename. The default filename for the ‘Blob’ object is a blob. The default filename is the file’s filename.

Example:

// FormData.set() - Set a field data in formdata.
    formdata.set('xyz', 'ABC');
    var set_data = formdata.get('xyz');
    console.log(set_data);

9. FormData.values():

This method is used to display the value of the respected key.

Syntax:

formData.values();

Example:

// FormData.values() - Display a value of repected keys.
    for (var value of formdata.values()) {
       console.log(value);
    }

Here is a full ajax code on how to get form data using formData.

jQuery(document).ready(function(){
  // AJAX Call For Form Data
  jQuery(document).on('submit','#form',function(event) {
    event.preventDefault();
        var formdata = new FormData(this);

        //FormData.append() - For a ther data can added in a formdata object
    	formdata.append('key', 'value');

    //FormData.entries() - For display a key/value of formdata object.
    for(var data of formdata.entries()) {
       console.log(data[0]+ ', '+ data[1]);
    }

    //FormData.delete() - For delete object form formdata
    formdata.delete('firstname');

    //FormData.get() - For getting first values of the associated key name
    var getdata = formdata.get('lastname');
    console.log(getdata);

    //FormData.getAll() - For getting all values of the associated key name
    	formdata.append('lastname', 'value1');
    	formdata.append('lastname', 'value2');
    var getdata = formdata.getAll('lastname');
    console.log(getdata);

    //FormData.has() - Return a Boolean value of respected a key
    var keyhas = formdata.has('key');
    console.log(keyhas);
    
    //FormData.keys() - display a key of respected value.
    for (var key of formdata.keys()) {
       console.log(key);
    }
    
    // FormData.set() - Set a field data in formdata.
    formdata.set('xyz', 'ABC');
    var set_data = formdata.get('xyz');
    console.log(set_data);
    
    // FormData.values() - Display a value of repected keys.
    for (var value of formdata.values()) {
       console.log(value);
    }
    
    jQuery.ajax({
      url : 'get_data.php',
      type : 'POST',
      data : formdata,
      contentType: false,
      processData:false,
      success : function(response) {
      },
      error: function(errorThrown){
        window.alert(errorThrown);
      } 
    });  
  });
});

Output:

You can see the output of form data in the browser console.

Thank You, hope you guys found something useful.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories