Hi, everyone!
Sometimes we have a task for creating form to submit via AJAX. But not all programmers know about the little piece of code for serializing the form with data for submitting.
; (function ($) {
// Example of usage: http://tobiascohen.com/files/stackoverflow/jquery-form-serializeObject.html
// This function is using for serializing form data to json.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
Example of using this code:
$.post("/submit_url", {data: $.toJSON($("#form1").serializeObject())}, function() {
alert('submited!!!');
});
That’s it