tags:

views:

53

answers:

3

I have search the net many times and a lot of the JSON tutorials are too hard to understand. I am looking for JSON with jQuery and PHP. if anyone knows any videos or website i can look at that would be great

Thanks

A: 

All you need is to understand that JSON is data in a different format. You can easily convert a PHP data structure into JSON (json_encode()), and parse a JSON string (json_decode()).

Check the PHP documentation for JSON (linked above) and the jQuery docs for $.ajax().

Ok, there comes an example.

The JavaScript:

$.ajax({
  url: 'json.php',
  success: function(data) {
    var ul = $('<ul></ul>');
    for(var i in data) {
      ul.append($('<li></li>')
          .append($('<strong></strong>').html(i))
          .append(': ')
          .append($('<span></span>').html(data[i]))
      );
    }
    $('body').append(ul);
  }
});

The PHP file:

<?php
$dbh = new PDO($connectionstring, $username, $password);
$response = array();
foreach($dbh->query('SELECT id, title FROM table ORDER BY id') as $record) {
  $response[$record['id']] = $record['title'];
}
print json_encode($response);

When The jQuery code runs, it requests data from the PHP file. The PHP file gets some content and print it as a JSON code. The response returns, the jQuery parses the JSON into data and fires the callback function.

Yorirou
yea but what are the chances ill be using json_decode if the decoding will be done through js?
sam
Your php scrpipt could receive a string with json-encoded data and then you'd use json_decode()
VolkerK
A: 

Not specifically json+php, but: Douglas Crockford - The JSON Saga

VolkerK
+1  A: 

What is JSON and how do I create JSON objects?

The only thing you should know is that JSON is actually Javascript code. You can create arrays and objects with values like strings and numbers (and arrays and objects again)

  • You can store a lot of values in an array, seperated by a comma, like this:

    [12, "string", -30] // This is an array with 3 values

  • You can store a lot of values seperated by commas in an object too, WITH your own key, like this:

    {"key1": "value1", "key2": 234} // This is an object with two pair of keys and values

The fun thing is that you can use arrays and objects as values. So, when you put everything you learned above together, you can get JSON code like this:

{                  // Creates an object
    "key1": 12,    // with a key called "key1" and a number as value
    "key2": [      // and another key called "key2", with an new array as value
        10,        // the array has the number ten as first value
        "value"    // and a string containing "value" as its second value
    ]
}

How can I use JSON?

You can use JSON as a simple way to transfer data between the server and the client, like the Twitter API does, for example.

On the client side you can send and receive JSON data via Javascript and AJAX. Often people use jQuery as a library for this, because it has some build in JSON-validation stuff. On the server side you can use PHP for the job to convert the JSON data to a PHP object.

You can access values this way in Javascript:

someArray[0]; // gives you access to the first value of an array
someObject.key; // gives you access to the value of an object with key 'key'

Let me give you an example in which you'll open the flickr stream:

// $.getJSON(url, dataHandlerFunction); to get JSON-data
// Add the first image of the Flickr stream to the page
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&amp;tagmode=any&amp;format=json&amp;jsoncallback=?", 
  function(data){

    // In this function you can do anything with the JSON code, because it's transformed into a Javascript object
    // If you open the above URL in your browser, you see that it exists of and object with
    // a key called items. Within is an array of objects, representing images
    // let's add the first one to our page
    var firstImg = data.items[0]; // First object, with image data.

    $("<img/>").attr("src", firstImg.media.m).appendTo('body');
  }
);

In PHP you can do almost the same:

// Get the JSON code form Flickr
$contents = file_get_contents('http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&amp;tagmode=any&amp;format=json&amp;jsoncallback=?'); 

// Decode it to a PHP object
$flickrStream = json_decode($contents);

// Display the image
echo '<img src="' . $flickrStream->items[0]->media->m . '" />';

Example: transfer data between client and server

You can use AJAX, as I said, to send data between the server and the client. Let me give you some simple example... You send something to the server, server sends something back.

// Sends a GET request to the server
$.ajax({
  url: '/to/your/php/file/',
  dataType: 'json',
  data: {
    "name": "client"
  },
  success: function(data){
    alert(data.messageFromServer); // alerts "Hi back, 
  }
});

PHP file (it's very unsafe this way, but it's a simple example)

<?php
  // A GET request was send, so you can use $_GET
  echo '{
          "messageFromServer": "Hi back, ' . $_GET['name'] . '"
        }';
?>
Harmen