Examples of Ajax

<<< Prev   1   2   Next >>>

Today's current temperature is: ???

The source code for this tiny, contrived example on the client:

var requester = null;
var uri = "http://www.fincher.org/tips/web/Ajax/Test.php";

//overall method to get current temperature
function showTemp() {
requester = getRequester(); 
requester.onreadystatechange = ajaxHandler;
requester.open("GET", uri);
requester.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"); //don't cache
requester.send(null);
}

//return an XHR object from any browser
function getRequester() {
    //if(requester != null) { return requester; } 
try { 
 requester = new XMLHttpRequest(); //try Opera, Firefox, IE7...
} catch (error) { 
 try  { 
   requester = new ActiveXObject("Microsoft.XMLHTTP"); //IE 6 and less
 }  catch (error) { 
   return null; 
 }
}
return requester;
}

//call back method
function ajaxHandler() { 
   if (requester.readyState == 4) { //wait til call is finished
      if (requester.status == 200) { //make sure its a good response
	  //document.getElementById("temperature").innerHTML = requester.responseText;
	  setTextField(requester.responseText);
      } else { 
         alert("Could not connect to server."); 
      }
   } else {
       setTextField(".................requester.readyState:"+requester.readyState);
   }
return true; 
}
function setTextField(mytext) {
   document.getElementById("temperature").innerHTML = mytext;
}

The php code on the server:

<?php
//don't you dare cache on me
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("content-type:text/xml");

sleep(1); 
srand((double)microtime()*1000000);

print (rand(60,105));
?>


<<< Prev   1   2   Next >>>