AJAX and JSON. How do I use it?

So I can’t for the life of me understand JSON. I’ve looked through numerous links but nothing. If I have a Database and all I want to pull is:

title => fight club
type = > movie
genre => action

how do I print that out to an HTML document using JSON. I don’t get it. I think it puts it in an array but how does it get there? Do I just print it out like I would a normal javascript array? If this isn’t quite the right place to post this I apologize but there wasn’t an AJAX section.

JSON essentially is just a normal array when it comes to grabbing data from it. For instance your grabbing data from your database that you want to be JSON, depending if your PHP version is 5.2 and above you can use a function called json_encode which transforms the regular PHP array into a JSON array. See the examples below…

// PHP Array
array('key_1' => 1, 'key_2' => 2);

// JSON Array
{key_1: 1, key_2: 2}

You can find all the information you need about AJAX using the following link AJAX Tutorial: XMLHttpRequest.

The other link you will need is a cross browser JSON parser as older browsers such as Firefox 3, Chrome 3 and IE 8 don’t support native JSON. Visit the following link for information about cross browser JSON parsing Cross browser JSON parsing | DBJ.ORG.

So more or less when you get the AJAX response from your server you can simply use the following to parse the response text.

var json = JSON.parse(xmlHttp.responseText);
alert(json.key_name);

That sounds pretty simple. So according to your above post I should be able to “alert” the value of key_1 via:

alert(json.key_1[0]); ?

It depends on the key names you specify, for example if your array return is like the below…

array(
    array('title' => 'Fight Club', 'type' => 'movie', 'genre' => 'action')
);

then your JavaScript would be like you have except without key_1, the only difference is it will be the following instead.

alert(json[0].title);

Ah gotcha! Thanks for your help!