jQuery serialize() method used to create a url encoded query string from form field values. This is used to send Ajax request by creating serialize data on click or load event. This way, you don't need to get one by one input value and send it to Ajax request.
Syntax:
$(selector).serialize();
Below example output the query string data of form fields when button clicks.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="text" name="name" value="Harsukh">
<input type="email" name="email" value="harsukh21@gmail.com">
<button type="button" id="button">Submit</button>
<p id="value"></p>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$('#button').click(function() {
var data = $('form').serialize();
$('#value').text(data);
});
</script>
</body>
</html>
In another way, jQuery serializeArray() method used to creates an array of objects from field values. This is similar to serialize() method except it creates array of object instead of query string. This method is usedful in sending Ajax request where json format data is required.
Syntax:
$(selector).serializeArray();
You can find the below example of use of serializeArray() method.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="text" name="name" value="Harsukh">
<input type="email" name="email" value="harsukh21@gmail.com">
<button type="button" id="button">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$('#button').click(function() {
var data = $('form').serializeArray();
console.log(data); // [{name:"name",value:"Harsukh"},{name:"email",value:"harsukh21@gmail.com"}]
});
</script>
</body>
</html>
Extra:
Ajax json data should be in key: value format. To create one level json data, you can use the below function.
function serializeObject(obj) {
var jsn = {};
$.each(obj, function() {
if (jsn[this.name]) {
if (!jsn[this.name].push) {
jsn[this.name] = [jsn[this.name]];
}
jsn[this.name].push(this.value || '');
} else {
jsn[this.name] = this.value || '';
}
});
return jsn;
};
This will return simple json object for the above example. If you want to add more data into json before Ajax request send, you can use Javascript push() method to add more data into json and send Ajax.
console.log(serializeObject(data)); // {name: "Harsukh", email: "harsukh21@gmail.com"}
I hope it will help you.