Skip to content

Instantly share code, notes, and snippets.

@eyy
Created July 4, 2013 13:16
Show Gist options
  • Save eyy/5927633 to your computer and use it in GitHub Desktop.
Save eyy/5927633 to your computer and use it in GitHub Desktop.
get form data as an object, and send form as ajax
/*
$('form').serializeObject() get form data as an object
$('form').formJSON(callback) send form as ajax
example:
$('form[data-json]').formJSON(function(res) {
$('h3.message').text(res.message);
});
*/
(function($) {
$.fn.serializeObject = function () {
var arr = this.serializeArray(),
o = {};
$.each(arr, function () {
var value = this.value != null ? this.value : '';
if (o[this.name] != null) {
if (!o[this.name].push)
o[this.name] = [o[this.name]];
o[this.name].push(value);
} else {
o[this.name] = value;
}
});
return o;
};
$.fn.formJSON = function(success, error) {
this.on('submit', function(e) {
e.preventDefault();
var t = $(this);
$.ajax({
type: t.attr('method') || 'post',
url: t.attr('action'),
data: JSON.stringify(t.serializeObject()),
dataType: 'json',
processData: false,
contentType: 'application/json',
success: success,
error: error,
context: t
});
})
};
})(jQuery);
@eyy
Copy link
Author

eyy commented Sep 5, 2013

Now a bower component: https://github.com/eyy/send

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