15
Oct
2011

Posting JSON with jQuery and PHP

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.

This entry was posted in Programming and tagged , , by Chris. Bookmark the permalink.

2 thoughts on “Posting JSON with jQuery and PHP

  1. Hi there,

    Does your solution also work with arrays? I am testing and i can’t get it to work with json arrays?

    regards

  2. Do you have your code someplace I could take a peak at it?

    For an array you should just be able to make the $jsonObj variable = your array.

    Let me know if that helps at all.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

flickr

  • IMG_3625
  • IMG_3582
  • IMG_3573
  • IMG_3558
  • IMG_2536
  • IMG_1890
  • IMG_2141

twitter