If you're using AJAX with a form and you want to pass a JSON object to one of the jQuery's AJAX methods used to process the request, you will probably wonder how this could be done. Basically, you should convert your form values to a plain array, loop through all the items in the array and finally return a plain object literal. Let's see the details.
We can put all the aforementioned routines in a simple jQuery plugin:
(function($) { $.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; }; })(jQuery);
We start with an empty object literal which will be populated by looping through the array returned by the serializeArray()
function. Here's a use case:
$('#contact').submit(function(e) { var $form = $(this); var data = $form.serializeFormJSON(); $.post('process.php', data, function(output) { // do something here }); e.preventDefault(); });
Hey Gabriele
Thanks for the great plugin. Appreciate you sharing!
Clay
Thanks for the plugin, very helpful. However, I think there's a small bug in Line 7. It should be:
if (o[this.name] !== undefined) {
Otherwise, if there are multiple values and the first one is "falsy", it will be overwritten.