AJAX Auto Load
If you take a look at dynamic websites, the content of the website will be refreshed automatically without user intervention. Example – CricInfo in which the score card will be refreshed in a time interval and display the latest score.
The example which we are going to develop will refresh the ‘DIV’ block for every 5 seconds and display the current web server’s time.
Here is the demo:
Steps to create auto load DIV:
Create HTML DIV block
Create a simple DIV which will be loaded with response from the server (time).
<div id="time"> <!-- Load Server Time --> </div>
Create XMLHttpRequest object
Create XMLHttpRequest object specific to the browser.
var xmlhttp; function createObject() { if (window.XMLHttpRequest) { // Mozilla, Safari, ... xmlhttp= new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { xmlhttp= new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } return xmlhttp; if (!xmlhttp) { alert("No. Giving up Cannot create an XMLHTTP instance. Your browser is outdated!"); return false; } }
Call setInterval JavaScript function
JavaScript function setInterval(function(),Milliseconds) is used to call the function() – Parameter 1 of the function for every MilliSeconds interval specified as Parameter of the function.
var auto = setInterval(function callTimer(){ var param = "t="+Math.random(); xmlhttp = createObject(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4){ if(xmlhttp.status==200){ document.getElementById("time").innerHTML=xmlhttp.responseText; } } } xmlhttp.open("GET","http://programmerguru.com/ajax-demos/server_time.php?"+param,true); xmlhttp.send(); }, 5000);