Categories: jQuery

Encode a set of form elements as a string

Share

The serialize() method creates a text string in standard URL-encoded notation by serializing form values.

One or more form elements (input, radio, checkbox etc.) can be used as a serializing.

You can use this serialized values as a URL query string while making an AJAX request.

Syntax:

$(selector).serialize()

Below we have shown an example for form serialize:

HTML:

<form action-xhr="#" method="post">
First Name:<input type="text" name="fname" /> <br/>
Last Name:<input type="text" name="lname" /> <br/>
Quota:<input type="checkbox" name="quota" value="Yes"/><br/>
<input type="submit" name="submit" id="submit" />
</form>
<pre id="result"></pre>

JQUERY:

$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serialize()));
return false;
});
});

Learn about JSON.stringify() for more details.

The JSON.stringify() method converts a JavaScript value to a JSON string i.e. optionally replacing the values if a replacer function is specified or optionally includes only the specified properties when a replacer array is specified.

VIEW:

The output will be:

"fname=john&lname=doe&quota=Yes"

Note: JSON.stringify converts a JavaScript value to a JavaScript Object Notation (JSON) string.

Read Also:  jQuery jQuery’s Data Method

Note that the JSON is not a completely strict subset of JavaScript with the two line terminators i.e.line separator and paragraph separator which is not needing to be escaped in JSON but needing to be escaped in JavaScript.

Recent Posts

Overview of Reputation, Services, and Features of IplWin

IplWin stands as a reliable and enthralling platform for Indian punters, offering a captivating blend…

2 days ago

Blogging Brilliance: Driving Traffic and Engagement with Quality Content

Introduction In today's online age, consumers are constantly bombarded with information. They crave valuable content…

3 days ago

How Assisted Living Gives Seniors More Freedom

In today’s rapidly aging society, finding a living situation that provides older adults with both…

3 days ago

Should you go for a Refurbished Mac?

If you wish to purchase a Mac, then it is strongly suggested to consider purchasing…

3 days ago

How Many Types of Bits are Used in Drilling Operations?

Oil drilling is a complex process that involves several components, including the drilling bit. The…

4 days ago

Best Watches to Match Your Business Look

Watches can be more than a fashion. They can be a symbol, especially in the…

4 days ago