Skip to content

Instantly share code, notes, and snippets.

@brianpeiris
Forked from danwrong/gist:175591
Created October 16, 2009 17:41
Show Gist options
  • Save brianpeiris/211909 to your computer and use it in GitHub Desktop.
Save brianpeiris/211909 to your computer and use it in GitHub Desktop.
A serializeHash plugin for jQuery that allows you to submit a form using jQuery's ajax functions.
/***
The serializeHash method can be used to submit forms with an ajax request.
The result of serializeHash can be used as the 'data' option for jQuery's
built-in ajax methods and functions.
***/
(function($){
$.fn.serializeHash = function() {
var hash = {};
/***
Use serializeArray() to get an array of JSON objects for
each value in the form.
(As opposed to serialize() which requires string splitting)
***/
$.each(this.serializeArray(), function() {
if(hash[this.name] === undefined) {
hash[this.name] = this.value;
}
else {
/***
Handle form elements with multiple values such as
<select multiple="multiple"> and multiple
<input type="checkbox"/> elements with the same name.
***/
if ($.isArray(hash[this.name])) {
hash[this.name].push(this.value);
}
else {
hash[this.name] = [hash[this.name], this.value];
}
}
});
return hash;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment