Reputation: 57974
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??
Upvotes: 2
Views: 3023
Reputation: 539
You can use this lib, $.serializeObject
is a variant of existing $.serialize
method which, instead of encoding form elements to string, converts form elements to a valid JSON object which can be used in your JavaScript application.
https://github.com/hongymagic/jQuery.serializeObject
Upvotes: 0
Reputation: 630349
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.
Upvotes: 2