Bug Tracker

Opened 6 years ago

Closed 6 years ago

Last modified 6 years ago

#12937 closed feature (plugin)

Add a $.fn.serializeJSON

Reported by: roche.jul@… Owned by:
Priority: undecided Milestone: None
Component: unfiled Version: 1.8.3
Keywords: Cc:
Blocked by: Blocking:

Description

Hi,

Sometimes, we need to convert the data from a form into JSON to send it with Ajax.

I've put now in my projects a code which can do this feature:

     /**
     * With this approach, we can serialize data (from a form for example) as a JSON object !
     */
     $.fn.serializeJSON = function () {
         var o = {};
         var a = this.serializeArray();
         
         // Retrieve data
         $.each(a, function () {
             if (o[this.name] !== undefined) {
                 if (!o[this.name].push) {
                     o[this.name] = [o[this.name]];
                 }
                 o[this.name].push(this.value || "");
                 
             } else if(this.name.match(/\[\]$/g)){
                 o[this.name] = [];
                 o[this.name].push(this.value || "");
                 
             } else {
                 o[this.name] = this.value || "";
             }
         });
         
         // Now clean parameters name
         for(var name in o){
                 if(name.endWith("[]")){
                         o[name.replace(/\[\]$/g, "")] = o[name];
                         delete o[name];
                 }
         }
         
         return o;
     };

An example of use:

$.ajax(
        "/mail",
        {
                method: "POST",
                contentType: "application/json",
                processData: false,
                data: JSON.stringify($("form:first").serializeJSON())
        }
);

Hope that can helped

Cheers

Julien Roche

Change History (3)

comment:1 Changed 6 years ago by roche.jul@…

Oups, I mean for my example:

$.ajax(
        "/mail",
        {
                type: "POST",
                contentType: "application/json",
                processData: false,
                data: JSON.stringify($("form:first").serializeJSON())
        }
);

comment:2 Changed 6 years ago by dmethvin

Resolution: plugin
Status: newclosed

Looks like a great plugin. The official jQuery plugin site will be launching soon and you could add it there.

comment:3 Changed 6 years ago by mark@…

I think this should be core. I don't think there are many use cases for serializeArray (yet this is core) but there are many, many use cases for serializeJson (yet this must be a plugin).

The main use case is servers-side AJAX data-biding. Grails for example can databind JSON object, but not the native name/value array that serializeArrray can. I've in fact never used serializeArray before, only plugins.

:)

Note: See TracTickets for help on using tickets.