jQuery - Serialization in jQuery

What is Serialization?

  • Serialization means converting form data into a query string format that can be easily sent to a server (usually with AJAX).

  • The method .serialize() collects all form input values (with name attributes) and turns them into a URL-encoded string.


Syntax

$(formSelector).serialize();

Example

HTML Form

<form id="myForm">
  <input type="text" name="username" value="John">
  <input type="email" name="email" value="[email protected]">
  <input type="checkbox" name="subscribe" checked>
  <button type="submit">Submit</button>
</form>

jQuery

var data = $("#myForm").serialize();
console.log(data);

Output

username=John&email=john%40example.com&subscribe=on

Why Use .serialize()?

  1. Simplifies gathering form data — no need to get each input manually with .val().

  2. Works great with AJAX:

    $.post("submit.php", $("#myForm").serialize(), function(response) {
       console.log("Server says:", response);
    });
    

Key Points

  • Only includes form elements with a name attribute.

  • Automatically URL-encodes special characters (e.g., @ becomes %40).

  • Skips disabled fields and buttons.