Are you at the stage in your AJAX development where using plain text to transfer your data just is not working anymore? And your fed up with all the <?xml buzz? Well why not wet your feet with some JSON – its easy, and lightweight.
First off lets create our PHP script that will query the database and then print out the data in JSON format.
<?php
// connect to db
include 'dbconnect.php';
// json library http://mike.teczno.com/JSON/JSON.phps
include 'json.php';
// query
$sql = “SELECT * FROM table”
$result = mysql_query($sql);
while( $row = mysql_fetch_array($result) )
{
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$ajax_data = array(‘first_name’=>$first_name,’last_name’=>$last_name);
// encode data into json
$json = new Services_JSON();
echo $json->encode($ajaxData);
}
?>
Now that we have the JSON being printed out from the above PHP script we can create our JavaScript to read this data and update the page.
<!-- Using an XMLHttpRequest Wrapper class -->
<!-- As well as http://www.json.org/json.js -->
var client = new HttpClient();
client.isAsync = 'true';
client.requestType = 'post';
client.responseType = 'TEXT';
client.callback = function(result){
var person = result.parseJSON();
// now we have access to the properties we put in the array
alert(person.first_name);
}
client.makeRequest(phpscript.php,”);
I hope this little tutorial puts the fun back into ajax again. This shows the power of passing massive objects and arrays from php into javascript which can then manipulate the DOM
Below is a quick list of useful DOM functions for those new to it:
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!