Posting JSON with jQuery and PHP

Posting JSON with jQuery and PHP

Posted on October 15, 2011 by

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.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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',
    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.

1
2
3
4
5
6
7
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.

Advertisements
By Rz Rasel Posted in jQuery

One comment on “Posting JSON with jQuery and PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s