Skip to content

Instantly share code, notes, and snippets.

@Neoglyph
Created July 4, 2017 07:50
Show Gist options
  • Save Neoglyph/85c50d6302802047e3c12df4acbd5f55 to your computer and use it in GitHub Desktop.
Save Neoglyph/85c50d6302802047e3c12df4acbd5f55 to your computer and use it in GitHub Desktop.
Serialize form data to JSON with jQuery
$.fn.serializeFormJSON = 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;
};
@Neoglyph
Copy link
Author

Neoglyph commented Jul 4, 2017

Used:

 $('#form-id').on('submit', function(e) {
        e.preventDefault();
        var json = $(this).serializeFormJSON();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment