Example 1 — Serialize on submit
Official pattern: prevent navigation and read the query string.
$("#contact-form").on("submit", function (event) {
event.preventDefault();
var data = $(this).serialize();
$("#output").text(data);
// Optional: $.post($(this).attr("action"), data);
});
Submit → preventDefault
#output shows
name=Jane&email=jane%40example.com&message=Hello...
How It Works
- Intercept. The submit handler runs before the browser navigates.
- Stop reload.
preventDefault() keeps the user on the page. - Serialize.
$(this).serialize() reads named successful controls.
Example 2 — Live Preview on Change
Adapted from the jQuery docs demo: update the string as controls change.
function showValues() {
var str = $("form").serialize();
$("#results").text(str || "(empty — no successful controls)");
}
$("input[type='checkbox'], input[type='radio']").on("click", showValues);
$("select").on("change", showValues);
$("input[type='text']").on("input", showValues);
showValues();
Toggle checkbox → #results updates
Uncheck control → that name drops out
Change select → new value appears encoded
How It Works
- Bind. Listen for click / change / input on controls.
- Read. Each event calls
$("form").serialize() again. - Reflect. The string always matches the current DOM state.
Example 3 — $.post(url, $form.serialize())
Pass the serialized string as the POST body — common Ajax form pattern.
$("#save-form").on("submit", function (event) {
event.preventDefault();
var $form = $(this);
$.post(
$form.attr("action"),
$form.serialize(),
function (data) {
$("#status").text("Saved! Server id: " + data.id);
},
"json"
);
});
serialize() → title=...&body=...&userId=1
$.post sends that string as the body
Success shows the new server id
How It Works
- Build string.
.serialize() creates form-urlencoded data. - POST. The second argument to
$.post() is that string. - Send as-is. jQuery posts it as the request body.