Custom Search

Basic AJAX Demo

This article illustrate on writing AJAX code and how to fetch data from remote server. Here i am calling a remote PHP page using AJAX. Below are the HTML page code followed by the PHP page code and finally provided with the explanation for the code. If you want to test this code online i have also provided with the link to Basic Ajax Demo.

Execute AJAX Demo






HTML Page Code:

<html>
<head>
<title>Ajax and PHP Demo</title>
<script type="text/javascript">
var xmlhttp = new getXMLObject();
var time_variable;
 
function getXMLObject()  //XML OBJECT
{
   var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
   }
   catch (e) {
     try {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
     }
     catch (e2) {
       xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
     }
   }
   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
   }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}
 
function ajaxFunction() {
  var getdate = new Date();  //Used to prevent caching during ajax call
  if(xmlhttp) { 
    xmlhttp.open("GET","ajax_time.php?" + getdate.getTime(),true);
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.send(null);
  }
}
 
function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       document.myForm.time.value=xmlhttp.responseText; //Update the HTML Form element 
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
}
</script>
<body>
<form name="myForm">
Server Time:<input type="text" name="time" />
<br />
<input type="button" onClick="javascript:ajaxFunction();" value="Click to display Server Time on Textbox"/>
</form>
</body>
</head>
</html>

PHP Code

< ?
   echo date("H:i:s");
?>

Explanation for the AJAX Demo Code

Here i have declared 3 JavaScript function:
getXMLObject() - Responsible for creating the AJAX Object depending on the browser.
ajaxFunction() - Responsible for calling remote script through AJAX call.
handleServerResponse() - Responsible for displaying the data retrieved from the server.

How the AJAX Code Works:

Execute AJAX Demo

Related Post

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)