Sr. Web Developer
mediabistro.com
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume

AJAX and PHP Part 1 - Dynamic HTML and Images
So you're interested in AJAX? AJAX is a powerful addition to JavaScript for browser-to-server intercommunication. We will demonstrate a simple script that sends a GET or POST request to a form handling script on a server, then the server script will return a response to the browser XMLHttpRequest JavaScript object.
A brief technical explanation of AJAX
AJAX is a client/server system. It is a standard that is compatible with all versions of IE browsers, Mozilla/Firefox browsers, the Opera browser and some others. Any browsers that were released in the last few years will work. It uses a JavaScript object commonly referred to as the XMLHttpRequest object within the client-browser HTML page, though there are some variations of this object in MS Internet Explorer browsers. We will demonstrate a simple script that is compatible with all browsers. You use this XMLHttpRequest object to simply send a GET or POST request to a Form handling script on a server, then the server script returns a response to the browser XMLHttpRequest JavaScript object. This text response can be plain text, HTML text with all tags and images or an XML-structured document.
In Part 2 we will cover XML document usage, but here we will cover plain text and full HTML text and images dynamically downloaded using the XMLHttpRequest object. Because the server only needs a script which can handle standard form requests, those being GET or POST, you can thus use Microsoft IIS server, Apache server with PHP or Perl, and Tomcat or any Java-based server. Our examples are of course PHP-based, and have been tested on a Linux Apache/PHP-based server with various browsers.


AJAX Example client #1
To get started, we will provide you with the full text listing of our client JavaScript/DHTML page, and we will be assuming you know something about JavaScript and HTML. This HTML page will make a GET request to a PHP server script named "getajax.php". That server script will then return a response in HTML which includes image links so the client browser can then use JavaScript to update certain elements of the page, dynamically showing the formatted HTML and images, and no refreshing of the client page will occur--that is the beauty of AJAX.
In the following HTML example, note the important factors of AJAX:
  1. The function getXHTTP() creates an XMLHttpRequest object for any browser, and returns that object.
  2. The var http = getXHTTP(); statement puts the XMLHttpRequest object into the http variable.
  3. The function doHttpRequest() uses the http variable with the http.open method and the http.send method to do the data request to the PHP server script located at http://www.jdcampbell.com/ajax/getajax.php.
  4. Also, the function doHttpRequest() contains the statement http.onreadystatechange = getHttpRes; which specifies the getHttpRes function as the handler function for the requested data, and this handler function is automatically called when the data is received from the PHP server script.
Here is the full HTML listing including all required JavaScript functions:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>

<title>Advanced AJAX Part 1</title>

<script language="javascript"  type="text/javascript">

function doHttpRequest() {  // This function does the AJAX request
  var c = document.getElementById("code").value; 
  http.open("GET", "http://www.jdcampbell.com/ajax/getajax.php", true);
  http.onreadystatechange = getHttpRes;
  http.send(null);
}

function getHttpRes() {
  if (http.readyState == 4) { 
    res = http.responseText;  // These following lines get the response and update the page
    document.getElementById('txt1').value = res;
    document.getElementById('div1').innerHTML = res;	
    document.getElementById('cell1').innerHTML = res;
  }
}

function getXHTTP() {
  var xhttp;
   try {   // The following "try" blocks get the XMLHTTP object for various browsers…
      xhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
 		 // This block handles Mozilla/Firefox browsers...
	    try {
	      xhttp = new XMLHttpRequest();
	    } catch (e3) {
	      xhttp = false;
	    }
      }
    }
  return xhttp; // Return the XMLHTTP object
}

var http = getXHTTP(); // This executes when the page first loads.

</script>

</head>

<body>

<form action="post">
Enter code: <input type="text" size="5" name="code" id="code" onblur="doHttpRequest();" /> <input type="button" value="Press" name="btn">
<br><br><br>
Return data...
<textarea id="txt1" name="txt1" rows="5" cols="60" style="width: 100%">empty</textarea>
</form>

<div id="div1">Some text.</div>

<br>

<table width=100% border=1 cellspacing=0>
   <tr><td id="cell1">cell1</td><td>cell2</td><tr>
</table>

</body>
</html>
The above code references a PHP server script at http://www.jdcampbell.com/ajax/getajax.php (the getajax.php script is live on the web). So you could actually copy the above client #1 script to your computer, run it, and it will work and do an AJAX dynamic download and update of your browser page. However, if you have access to any PHP-based Web server you can put the getajax.php script on your server and edit it to return any DHTML data you wish to be dynamically displayed in your AJAX client browser page. The HTML/text returned by the server script should not include the and and tags.
AJAX client #1 described
When this page first loads the script, line var http = getXHTTP() is executed. This creates a newly created XMLHttpRequest object for use by this AJAX client in the various JavaScript functions. Then it makes a call to doHttpRequest() when the user changes focus (that is the onblur event) from the Input text box named "code"; this onblur event of the "code" textbox is what initiates the AJAX request process by calling the doHttpRequest() function. At this point, the client HTML page has no changes. When the XMLHttpRequest object receives a response from the server PHP script, the function getHttpRes() is automatically called, which updates the specific client HTML page elements with the data returned by the PHP server script. These are the lines which update the HTML client page elements:
    document.getElementById('txt1').value = res;
    document.getElementById('div1').innerHTML = res;	
    document.getElementById('cell1').innerHTML = res;
The JavaScript statements above take the contents of the res variable (which contains the returned data of the AJAX request) and updates the "txt1" Textarea element contents, and the "div1" Div HTML element contents, and the "cell1" Table cell element contents. All of these elements are within the last 14 lines of the client #1 HTML page listing above.
If you know a little about JavaScript and HTML, then you know that some elements of an HTML page can contain full HTML, such as div sections and table cells, and as long as you specify an id="idname" attribute of these elements you can dynamically update them. Other HTML elements like textareas and textboxes of forms can only contain plain text. That is why the first line of our code snippet above uses the property assignment of .value = res (for plain text) and the last two lines of the snippet use the assignment of .innerHTML = res (for full HTML). The last two lines with the .innerHTML = res assignment are assigning the AJAX server response data which is full HTML to the div1 and cell1 page elements with those exact ids. When this occurs, you will see the contents of the table cell1 change to some dynamic HTML, including an image. Additionally, the div1 section will show the same HTML/image content.


For developing AJAX-powered HTML pages which produce dynamic HTML content within elements of the page, you will use the .innerHTML property assignment a lot. Almost any HTML page element that supports this .innerHTML property can contain dynamically updated HTML. You could check a JavaScript reference to see all the HTML page elements that support the .innerHTML property, but basically the "innerHTML" property can be updated (read/write) for all objects in DHTML except the following: COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, and TR.
AJAX server-side PHP script "getajax.php
The PHP script which we used to support our AJAX client #1 example above is very simple:


<?php
echo "<IMG src='http://www.jdcampbell.com/14.gif'><br>This is an Ajax/PHP response.<br>What do you think?<br>";
?>


Place the above text in a file named "getajax.php" on your PHP Web server and it'll work just fine. However, if you use it with our client #1 example, you will need to change the web address to your server within the function doHttpRequest() near the top of the client #1 HTML document.
Look for Part 2 of this tutorial on "Advanced AJAX used with PHP" for more AJAX technology. Primarily what we will be discussing in future articles is database operations with AJAX requests, and XML document download and usage via AJAX, and maybe a few other related issues. See you then!