Send JSON using AJAX

Is there anything special I have to do for a JSON object before sending it using AJAX? My code is as follows:

runAjax(JSON.stringify(data)); 

}

 function runAjax(JSONstring) { ajax = getHTTPObject(); var params = "?data=" + JSONstring; ajax.open("POST", "createtrip.php", true); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajax.setRequestHeader("Content-length", params.length); ajax.setRequestHeader("Connection", "close"); ajax.onreadystatechange = serverSpeaks; ajax.send(params); } 

Now the server is not receiving data. I get null on the server side, but the client side of JSONString is installed. Is there something I'm doing wrong?

+4
source share
3 answers

You send data via POST, you do not need the character '?' at the beginning of the params variable, I also recommend you encode JSONString to avoid problems.

Note that you are not given the var statement for the ajax variable, this declares it globally (window.ajax), and I think you don't need it globally ...

 function runAjax(JSONstring) { var params = "data=" + encodeURIComponent(JSONstring), ajax = getHTTPObject(); ajax.open("POST", "createtrip.php", true); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajax.setRequestHeader("Content-length", params.length); ajax.setRequestHeader("Connection", "close"); ajax.onreadystatechange = serverSpeaks; ajax.send(params); } 
+5
source

You must go through the encoder to send data correctly. Of course, first you will need to see that the variable "data" is well formed as "JSON".

lib for encoding / decoding

another link to encode / decode

0
source

The server can deal with the body post, as name1 = value & name2 = value2.

If you use PHP, you can get the json string:

 $data = file_get_contents("php://input"); 
0
source

All Articles