After looking around the net some, and having this issue before, I decided to put this up for anyone who might be having the same trouble as I once had. Posting JSON with PHP can be a bit tricky if it’s your first time doing this.
So for starters, lets download some scripts we’ll need to make this work.
- https://github.com/douglascrockford/JSON-js/blob/master/json2.js
- http://code.jquery.com/jquery-1.6.4.min.js
json2.js
This file will be used for taking a javascript object and converting it to a string.
jQuery
This is my javascript library of choice. So for this example I will be using this.
Javascript Time!
So lets get our hands dirt with some javascript. Here is a simple AJAX post using javascript and using the JSON.stringify to convert our object to a string so we can post it. While I don’t actually show it. Make sure to include the json2.js file and in this case, jQuery on the page.
// Declare a variable
var jsonObj = {demo: 'this is just a simple json object'}
// Lets convert our JSON object
var postData = JSON.stringify(jsonObj);
// Lets put our stringified json into a variable for posting
var postArray = {json:postData};
$.ajax({
type: 'POST',
url: "http://somedomain.local.com/phpfile.php",
data: postArray,
success: function(data){
// Do some action here with the data variable that contains the resulting message
}
});
PHP in The House
In our php file, we can process the post variable. First we check and see if we actually have post variable. Next, we need to strip the slashes out of the string which were put in for transport. Then we just run the json_decode php function. After that we can access the php object and use it however we like.
if(isset($_POST["json"])){
$json = stripslashes($_POST["json"]);
$output = json_decode($json);
// Now you can access your php object like so
// $output[0]->variable-name
}
This is a pretty basic and watered down example but hopefully it will help you.