Top » AJAX » GET DATA

Getting Data from the Server

Using AJAX, sometimes you need to get data from the server.
This bit of code will retrieve data from a server:

<script>
function ajaxNow()
{
  var xmlHttp;
  try
  {
    /* Firefox, Opera 8.0+, Safari */
    xmlHttp=new XMLHttpRequest();
  }
  catch (e)
  {
    /* newer IE */
    try
    {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      /* older IE */
      try
      {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        alert("Your browser is old and does not have AJAX support!");
        return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
  {
    if(xmlHttp.readyState==4)
    {
      /* this puts the value into an alert */
      alert("Value read is: "+xmlHttp.responseText);
    }
  }
  xmlHttp.open("GET","ajax_file.php",true);
  xmlHttp.send(null);
}
</script>
In this code, you will need to have a form or object to show the data. You need to have a file on your server (ajax_file.php noted above) which will send output (STD-OUT for the server file). The above function needs to be called at some interval on some event.