Skip to main content

Bug Tracker

Side navigation

#12937 closed feature (plugin)

Opened November 21, 2012 01:50PM UTC

Closed November 21, 2012 05:53PM UTC

Last modified December 29, 2012 06:18AM UTC

Add a $.fn.serializeJSON

Reported by: roche.jul@gmail.com 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:

#!js
     /**
     * 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:

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

Hope that can helped

Cheers

Julien Roche

Attachments (0)
Change History (3)

Changed November 21, 2012 01:54PM UTC by roche.jul@gmail.com comment:1

Oups, I mean for my example:

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

Changed November 21, 2012 05:53PM UTC by dmethvin comment:2

resolution: → plugin
status: newclosed

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

Changed December 29, 2012 06:18AM UTC by mark@foxbomb.com comment:3

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.

:)