Home Programming AJAX Example

Search

AJAX Example Print
Written by Chris Gountanis   

This program demonstrates AJAX by using a PHP page to refresh the time without full page refreshing.

  

PAGE CODE: AJAX.HTML

<script type="text/javascript">

function ajaxFunction() {

var xmlHttp;

try {

// IE 7.0+, Firefox, Opera 8.0+, Safari

xmlHttp=new XMLHttpRequest();

} catch (e) {

// Internet Explorer 6 and supported below

try {

xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {

alert("Your browser does not support AJAX!");

return false;

}

}

}

 

xmlHttp.onreadystatechange=function() {

if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {

document.myform.time.value=xmlHttp.responseText;

}

}

 

// get page content with random number to prevent caching

xmlHttp.open("GET", "time.php?id=" + Math.random(), true);

xmlHttp.send(null);

}

</script>

 

<br><br><div>Type and the time will displayed using AJAX. </div><br>

<form name="myform" action="">

<div>Enter Text Here:</div>

<div><input type="text" onkeyup="ajaxFunction();" name="username"></div>

<div>Time:</div>

<div><input type="text" name="time" disabled></div>

</form>

PAGE CODE: TIME.PHP

<?php

echo(gmstrftime("%X",time()));

?>

Last Updated on Saturday, 09 February 2008 20:59