AJAX / JSON Guide

 

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:

  • document.getElementById(‘id’)
  • node.getAttribute(‘attribute’)
  • node.childNodes
  • document.createElement(‘element’)
  • node.appendChild(newNode)
  • element.innerHTML
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Add to favorites
  • Design Float
  • DZone
  • email
  • FriendFeed
  • PDF
  • Propeller
  • Reddit
  • RSS
  • StumbleUpon
  • Twitter

Related posts:

  1. Plain Text, XML, and JSON Transfer Formats
  2. Really Simple Model/View Seperation With PHP
  3. A Geeks Guide to VI
  4. How to Create a Simple API with PHP and MySQL
  5. CodeIgniter PHP Framework


Written by Brenley Dueck

 

Leave a Reply

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

 
connect with me!