Check out this function and helper I created for serializing a javascript object to send in an ajax request. While there may be more efficient solutions in libraries like jQuery, I couldn't find one specifically for a javascript object.
/*
@author Benjamin Yep
@important - THIS FUNCTION ASSUMES INPUT ENCODED ACCORDING TO RFC 3986. See here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
@param data - Any javascript object or array.
@param pName - The name of the object to be sent in your ajax request.
@return A serialized JSON-encoded object ready to be sent in a request.
Usage:
var someObject={
"foo":"bar",
"bars":["foo","bar"],
"object":{
"foo":1,
"bar":2",
},
};
var r=makeHttpObject();//new ajax object
r.open("get","example.php",false);
r.send(paramify(someObject,"varname"));
//In example.php
<?php
echo var_dump($_POST['varname']);
?>
//back in the javascript file
console.log(r.responseText);//displays the contents of the object you sent to the server
*/
function paramify(data,pName){
return constructObject(data,pName).substr(1);
}
function constructObject(data,path){
var contents="";
for(var key in data){
var curpath=path+"["+key+"]";
if(Object.prototype.toString.call(data[key])==='[object Object]'||data[key] instanceof Array){
if(!(data[key] instanceof Array)||data[key].length!=0){
if(JSON.stringify(data[key])=="{}"){
contents+="&"+curpath+"={}";
}else{
contents+=constructObject(data[key],curpath);
}
}else{
contents+="&"+curpath+"=[]";
}
}
else{
contents+="&"+curpath+"="+data[key];
}
}
return contents;
}