Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursive function to serialize a javascript object for an ajax request - is there an easier way?
    text
    copied!<p>Here is a function and helper that I wrote to serialize a javascript object for sending in an ajax request. Chances are there is a more efficient solution out there somewhere, probably in the jQuery library, but I can't find one. Not one for a javascript object.</p> <pre><code>/* @author Benjamin Yep @important - THIS FUNCTION ASSUMES INPUT ENCODED ACCORDING 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 send 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 &lt;?php echo var_dump($_POST['varname']); ?&gt; //back in the javascript file console.log(r.responseText);//shows 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+="&amp;"+curpath+"={}"; }else{ contents+=constructObject(data[key],curpath); } }else{ contents+="&amp;"+curpath+"=[]"; } } else{ contents+="&amp;"+curpath+"="+data[key]; } } return contents; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload