Thursday, February 18, 2010

Introduction to AJAX

AJAX or Asynchronous Javascript And XML is technology that facilitate the interaction with database or other external data without the need to reload the webpage.

This is made possible by the DOM API called xmlHttpRequest, which allows HTTP/HTTPS requests to be initiated and handled from within Javascript.

Simple Example of AJAX implementations
Reference from (Sample from cloudwisp.net)

Components
  • HTML with embedded Javascript file (*.js)
  • Database Table(e.g shoutOutTable)
  • PHP/ASP file to query the table (e.g PHP-getShoutOut.php)


/////////////////////
//function to place in your .js(javascript) file for the current document(html)
////////////////////
function xmlRequest(){
var xmlHttp=null;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp=new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
}
return xmlHttp;
}

function getShoutOuts(){
 var xmlObject=new xmlRequest();
 xmlObject.open("GET","getShoutOuts.php",true);
 xmlObject.send(null);
 xmlObject.onreadystatechange=function(){
  if (xmlObject.readyState==4){
   var returnString=xmlObject.responseText.split("|");
   if (returnString[0]=="OK"){
    //query was successful
    var returnedHTML=returnString[1];
    document.getElementById( ishoutContainer).innerHTML=returnedHTML;
   } else if (returnString[0]=="ERROR"){
    //query failed in php and reported an error
    alert(returnString[1]);
   }
  }
 }
 var t=setTimeout(getShoutOuts,10000);
}
/////////////////////

Database Table(shoutOutTable) in mysql

soID(int,auto_increment),userName(varchar 50),shoutOutMsg(varchar 255)


PHP File (getShoutOuts.php)


include "connect.php";
$sql="SELECT * FROM shoutOutTable ORDER BY soID DESC LIMIT 10";
$result=mysql_query($sql);
if (mysql_errno()){
 echo "ERROR|".mysql_error();
} else {
 echo "OK|";
 for ($row=mysql_fetch_assoc($result)){
  echo "".$row['userName'].": ".$row['shoutOutMsg']."";
 }
}

// this will return latest 10 shoutouts




Additional Info

xmlObject.readyState

The "readyState" property keeps track of the current stage of the request by returning an integer:
  • 0: uninitialized
  • 1: loading
  • 2: loaded
  • 3: interactive
  • 4: complete

No comments:

Post a Comment