Created
July 4, 2013 13:16
-
-
Save eyy/5927633 to your computer and use it in GitHub Desktop.
get form data as an object, and send form as ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
$('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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now a bower component: https://github.com/eyy/send