views:

31

answers:

1

I want to serialize a form into json, process the json object, then reserialize it to send to a php script via ajax.

Here is a rough example of what I want to do:

s = $('.dia_req_form').serialize();
j = //convert s to json ...HOW??
if(j.name)
{
    alert("you must enter a name");
}
if(selectedID)
{
    j.id = selectedID;
}
s = //serialize j ...HOW??

You can see the 2 parts that say HOW??

+1  A: 

You can use .serializeArray() and $.param() like this:

//validate here
var obj = $('.dia_req_form').serializeArray();
if(selectedID) {
  obj.push({ name: 'id', value: selectedID });
}
var s = $.param(obj); //s can be used for submission

Internally, .serialize() is really equivalent to $.param($(this).serializeArray()), so all this is doing is breaking the steps apart, adding an item if needed.

.serializeArray() is an array of objects with 2 properties (name and value), all we're doing is adding some object to the array if needed, then calling $.param() to make it a string.

Nick Craver