Serializar formulario a JSON con JQuery

Hoy estuve buscando una función que me permitiera serializar un formulario en JSON para mandarlos con AJAX y no tener que buscar uno por uno los elementos en el DOM , y la verdad que encontré esta función en JQuery que esta muy buena y es muy simple, espero les sirva.

$.fn.serializeObject = 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;
};

Aca va un ejemplo de Uso

$.ajax({
       url: URL_SITE + "my_controller/my_method",
       type: "POST",
       data: $("#frmMyForm").serializeObject(),
       success: function(r){
             //Response
       }
});
Both comments and pings are currently closed.

One Response to “Serializar formulario a JSON con JQuery”

  1. nacimiento dice:

    Good post but challenging to comprehend because I am from Germany ;-)

Subscribe to RSS Feed Seguinos en Twitter