Mar
12

AJAX and PHP, getting data on the fly.

by §ean

I find quite often that people shy away from Ajax because they feel it would be too hard to implement in to their site. This is usually not the case. This week will be the first of several tutorials that are intended to help give an understanding in to how AJAX can be used to dynamically change elements of a site. In this tutorial I will provide an AJAX engine that will be used in many other posts. I will also be discussing how to use this engine to bring data in from a PHP file and display that to a DIV on your site. Check out this example:

The AJAX engine:

function AJAX_Object()
{
  var xml_http;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xml_http = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xml_http = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xml_http = false;
      }
    }
  @else
  xml_http = false;
  @end @*/

  if (!xml_http && typeof XMLHttpRequest != ‘undefined’) {
    try {
      xml_http = new XMLHttpRequest();
    } catch (e) {
      xml_http = false;
    }
  }
  return xml_http;
}

The engine opens up a line of communication to your webserver allowing you to access information from a variety of sources. It originally was designed to pull data from an XML file, but I most commonly use it to gather information from PHP scripts that are run in the background.

Declare a new AJAX object instance:

var MrAjax = new AJAX_Object();

The first thing we need to do is create a new instance of the AJAX object. In this example I have called the new instance MrAjax, you of course may call it whatever you like. There may be a time when you need multiple instances of the object declared, that is the beauty of object oriented programming. With objects you can feel free to create multiple instances of the same object without them interfering with one another.

Send / Receive Function:

function get_data()
{
        var url="ajax1.php";
        MrAjax.open ("GET",url,true);
        MrAjax.onreadystatechange = recv_data;
        MrAjax.send(null);
}

function recv_data()
{
        if (MrAjax.readyState == 4)
        {
                if (MrAjax.status==200)
                {
                        document.getElementById("Ajax_Content").innerHTML=MrAjax.responseText;
                }
        }
}

In the first function we pass all of the necessary information in to the Ajax object. I created a variable called URL which contains the name of the php file we will be getting our data from. Next is MrAjax.open(”GET”,url,true); this opens up the communication pathway using the GET method, to the URL described above, and the true statement tells the object that it is asynchrinous connection, which is what makes Ajax possible. Finally we have MrAjax.onreadystatechange = recv_data; this calls the function recv_data() each time the readyState of the ajax engine changes.

There are several ready states, (0 - The request is uninitialized, 1 - The request is set up, but not sent, 2 - The request was sent and is in process, 3 - The request is in process; often some partial data is available from the response, but the server isn’t finished with its response, 4 - The response is complete; you can get the server’s response and use it) the one we want to wait for is 4. We will ignore the MrAjax.send statement, it needs to be there for things to work, but let’s not worry about that until another tutorial.

The next function, recv_data() is what was refered to by the onreadystatechange method of the object. The Ajax engine reports back to the browser with ready state and status codes that will be needed to know when the file is loaded and ready to go. This function makes sure those values are what they need to be, before calling the response text. Once the values are achieved, we use the innerHTML function to change the code inside the Ajax_Content DIV to what we pulled from the php file.

Bring it all together:

<p id="Ajax_Content">Old content
<input value="Change it up" onclick="get_data()" type="button" />

We of course need to create our DIV (Ajax_Content) and some method of running our function. I have chosen a simple button that when clicked will run the function get_data().

Let’s not forget the PHP file:

<?php
     echo ("Some new content");
?>

This is very simple, it just prints Some new content as the output. Whatever is outputted is what will display in the Ajax_Content DIV.

There you have it. A very basic intro to actual Ajax. I will be getting more complex in future tutorials, I just want to make sure that everyone has a nice grasp of how things work before getting in to all the heavy duty stuff. Be sure to download all of the source code used in this tutorial here.

Until next time, God Bless,
§ean

Tags: , , , , , ,

Related Posts

One Response to “AJAX and PHP, getting data on the fly.” RSS

  1. Sean Says:

    I think your Ajax code is fine and dandy, but to most people I’d recommend using a library like jQuery. jQuery makes Ajax so easy it’s really not even funny, and it also has the added benefit of making it fun to write any javascript in general. Before jQuery came along I never really used JS much at all, because of how hard it was to write code that worked correctly in all browsers.