Software Applications
Page tree

using Ajax in your webpage

Table of Contents

Topic Overview

Ajax stands for Asynchronous JavaScript and XML, it's not a new programming language but a new way to make website more dynamic. Ajax allows you to update part of the page without reloading the whole webpage.

Solution

1. Create anXMLHttpRequest object:

xmlhttp=new XMLHttpRequest();

for older version of IE(IE5, IE6):

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

2. Send a request to the server,

xmlhttp.open("GET","destination.php",true);
xmlhttp.send();

3. Write the actions you want to perform under onreadystatechange event, this event will trigger when the server is ready to response.(when readyState=4 and status=200)

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}

Example

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","destination.php",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h1>These text will be changed on click</h1></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>

This example will change the text to whatever it is in destination.php

Sources and Relevant Links


#top