#native_company# #native_desc#
#native_cta#

XMLHttpRequest and AJAX for PHP programmers, Part 2

By James Kassemi
on June 13, 2005

Let’s Jump Right In!

This week’s article takes off where last week’s tutorial left off–we’re about to jump into the creation of the PHP backend! If you haven’t read the previous article, we recommend that you begin there before moving forward so you don’t miss anything.

Calling the Functions

Now, how is the products.html page supposed to call these functions? We want to be able to let the user select an item, and then load the values based on that selection. Using a “Search” or “Go” button is a little archaic, so let’s use the onChange method, which we can use to call javascript functions whenever the user changes the selected item. Change the <select> tag in products.html to look like this:
[HTML code]
<select name="select_category_select" onChange="getProducts();">
Whenever a user changes his selection in the select box, getProducts() will be called. So, now that we’ve got a script that sends some data to a PHP file and receives data returned from a PHP file, we need to program the PHP file.

Programming the PHP back-end

In our javascript function getProducts(), we made a call to the following:
[javascript code]
	http.open('get', 'internal_request.php?action=get_products&id=' 
			+ document.getElementById('product_categories').selectedIndex);
So we obviously need a PHP script that handles the action and id arguments from a GET request.
[PHP code]

<?php

/* You should implement error checking, but for simplicity, we avoid it here */

if($_GET[‘action’] == ‘get_products’){

    
/* We’re here to get the product listing…

        You can obviously change this file to include many

        different actions based on the request.

    */

    
switch($_GET[‘id’]){

        /* We had the following in our list.

                0 Audio

                1 Games

                2 Internet

            The integer value on the left is the value

            corresponding to the javascript selectedIndex

            property.*/

        
case 0: // Audio Programs

            /* Print HTML to fill the product_cage <div>
                Any output to the browser will be

                retrieved in the XMLHttpRequest object’s

                responseText property */

            echo

                <ul>

                    <li>CDex</li>

                    <li>CoolEdit</li>

                    <li>Winamp</li>

                    <li>XMMS</li>

                </ul>’;

            break;

        case
1: //Games

            
echo

                <ul>

                    <li>Blackjack</li>

                    <li>Calculatron</li>

                    <li>Hold’em</li>

                    <li>Minesweeper</li>

                    <li>Tetris</li>

                </ul>’;

            break;

        case
2: //Internet

            echo

                <ul>

                    <li>Epiphany</li>

                    <li>Internet Explorer</li>

                    <li>Mozilla</li>

                    <li>Netscape</li>

                    <li>Opera</li>

                    <li>Safari</li>

                </ul>’;

            break;

        default:

            echo
‘<b>You didn’t select an item from above!</b>’;

            break;     

    }    

}

?>

Save the above in a file called internal_request.php.
Browse to products.html using your favorite browser, and select one of the category options. You’ll see the product_cage div change according to which items you selected. It may not seem like much with all the work that you put into it, but giving the user the ability to search and receive results while on the same page is great. Imagine posting to a forum without leaving the thread, or even something similar to the above for a large corporation with thousands of products. Bandwidth saved is money saved, and your company will no doubt appreciate that.
There are many resources available to learn more about AJAX and the XMLHttpRequest object, and now that you know the basics, you shouldn’t have any problem expanding your knowledge to fit your application. Good luck!

Source for Included File: products.html

<html>
	<head>
		<title>CompanyXYZ Software</title>
		<script language="javascript" type="text/javascript" 
			src="./internal_request.js">

		</script>
	</head>
	<body>
		<div id="product_categories">
			<!--Category selection box...-->
			<form name="form_category_select">

				<select name="select_category_select" onChange="getProducts();">
					<option>Audio</option>
					<option>Games</option>

					<option>Internet</option>
				</select>
			</form>
		</div>
		<div id="product_cage">

			<!--This is where we'll be displaying the products once they're loaded-->
			^ Please select a category from above.
		</div>
	</body>
</html>

Source for Included File: internal_request.js

/* The following function creates an XMLHttpRequest object... */

function createRequestObject(){
	var request_o; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	if(browser == "Microsoft Internet Explorer"){
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}
	return request_o; //return the object
}

/* You can get more specific with version information by using 
	parseInt(navigator.appVersion)
	Which will extract an integer value containing the version 
	of the browser being used.
*/
/* The variable http will hold our new XMLHttpRequest object. */
var http = createRequestObject(); 

/* Function called to get the product categories list */
function getProducts(){
	/* Create the request. The first argument to the open function is the method (POST/GET),
		and the second argument is the url... 
		document contains references to all items on the page
		We can reference document.form_category_select.select_category_select and we will 		
		be referencing the dropdown list. The selectedIndex property will give us the 
		index of the selected item. 
	*/
	http.open('get', 'internal_request.php?action=get_products&id=' 
			+ document.form_category_select.select_category_select.selectedIndex);
	/* Define a function to call once a response has been received. This will be our
		handleProductCategories function that we define below. */
	http.onreadystatechange = handleProducts; 
	/* Send the data. We use something other than null when we are sending using the POST
		method. */
	http.send(null);
}

/* Function called to handle the list that was returned from the internal_request.php file.. */
function handleProducts(){
	/* Make sure that the transaction has finished. The XMLHttpRequest object 
		has a property called readyState with several states:
		0: Uninitialized
		1: Loading
		2: Loaded
		3: Interactive
		4: Finished */
	if(http.readyState == 4){ //Finished loading the response
		/* We have got the response from the server-side script,
			let's see just what it was. using the responseText property of 
			the XMLHttpRequest object. */
		var response = http.responseText;
		/* And now we want to change the product_categories <div> content.
			we do this using an ability to get/change the content of a page element 
			that we can find: innerHTML. */
		document.getElementById('product_cage').innerHTML = response;
	}
}

Source for Included File: internal_request.php


<?php

/* You should implement error checking, but for simplicity, we avoid it here */

if($_GET['action'] == 'get_products'){
    
/* We're here to get the product listing...
        You can obviously change this file to include many
        different actions based on the request.
    */
    
switch($_GET['id']){
        
/* We had the following in our list.
                0 Audio
                1 Games
                2 Internet
            The integer value on the left is the value
            corresponding to the javascript selectedIndex
            property.*/
        
case 0: // Audio Programs
            /* Print HTML to fill the product_cage <div>
                Any output to the browser will be
                retrieved in the XMLHttpRequest object's
                responseText property */
            
echo '
                <ul>
                    <li>CDex</li>
                    <li>CoolEdit</li>
                    <li>Winamp</li>
                    <li>XMMS</li>
                </ul>'
;
            break;
        case
1: //Games
            
echo '
                <ul>
                    <li>Blackjack</li>
                    <li>Calculatron</li>
                    <li>Hold'em</li>
                    <li>Minesweeper</li>
                    <li>Tetris</li>
                </ul>'
;
            break;
        case
2: //Internet
            
echo '
                <ul>
                    <li>Epiphany</li>
                    <li>Internet Explorer</li>
                    <li>Mozilla</li>
                    <li>Netscape</li>
                    <li>Opera</li>
                    <li>Safari</li>
                </ul>'
;
            break;
        default:
            echo
'<b>You didn't select an item from above!</b>';
            break;     
    }    
}
?>