Nice work guys!
Hey Cris, here is a quick example to compliment the info Joel and Frank provided.
Unless your JavaScript script is fetching a JSON object from a server via AJAX, you have to manually build JSON objects as Frank described on page 1 in
Intro to JSON.
If you directly build the JSON object in JavaScript, it's an object, not a string. If you fetch a JSON object generated by a server via AJAX, it will return a JSON encoded string that's not yet an active object. Once you fetch the JSON data from a server, you have to use JavaScript
eval which will interpret the string as JavaScript. So if you assign that to a variable, the variable will become an active JSON object that you can access with dot notation as Frank described.
Here is a simple example:
<?php
// array fetched from database
'first' => 'Cris',
'last' => 'Cutas'
);
// create json encoded form
$jsonData = json_encode($data);
// json HTTP header as Joel mentioned
header("Content-Type: application/json");
// any HTTP cache related headers you need
header("Cache-Control: no-cache");
// send json string to client
?>
Then in JavaScript:
// note, jsonResponse here is the equivalent of httpRequest.responseText;
function handleJSONResponse(jsonResponse) {
var jsonObject = eval( '(' + jsonResponse + ')' );
alert(jsonObject.first); // alerts "Cris"
}
You may also want to read
this article on wikipedia. Cheers!