How can I send JSON data from Javascript to a server and have PHP parse it there?
feedback
|
I've gotten lots of information here so I wanted to post a solution I discovered. The problem: Getting JSON data from Javascript on the browser, to the server, and having PHP successfully parse it. Environment: Javascript in a browser (Firefox) on Windows. LAMP server as remote server: PHP 5.3.2 on Ubuntu. What works (version 1): 4) On the server, PHP code to read the JSON string: What works (version 2): The pitfall I ran into: References: | ||||
feedback
|
There are 3 relevant ways to send Data from client Side (HTML, Javascript, Vbscript ..etc) to Server Side (PHP, ASP, JSP ...etc)
HTML form Posting Request (GET or POST) This is most commonly used method, and we can send more Data through this method AJAX This is Asynchronous method and this has to work with secure way, here also we can send more Data. Cookie This is nice way to use small amount of insensitive data. this is the best way to work with bit of data. In your case You can prefer HTML form post or AJAX. But before sending to server validate your json by yourself or use link like http://jsonlint.com/ If you have Json Object convert it into String using JSON.stringify(object), If you have JSON string send it as it is. | |||||||
feedback
|
using JSON.stringify(yourObj) or Object.toJSON(yourObj) last one is for using prototype.js, then send it using whatever you want, ajax or submit, and you use, as suggested, json_decode ( http://www.php.net/manual/en/function.json-decode.php ) to parse it in php. And then you can use it as an array. | |||
feedback
|
PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object. In order to pass it as a string from Javascript, you can convert it to JSON using
or a library such as Prototype | |||
feedback
|
I recommend the jquery.post() method. | |||
feedback
|
| |||
feedback
|