Using Ajax with PHP, by Ben Mueller:

This tutorial will teach you the very basics of Ajax and show you how to create a simple Ajax application that uses a PHP script to read what a user has put into a text box and spit it back out as an alert. This Tutorial uses very little PHP and I recommend that you have some JavaScript and HTML experience before using this tutorial.


What is Ajax?

Ajax(short for Asynchronous JavaScript And XML), is a way of writing JavaScript in order to communicate with the server smoothly and quickly. Instead of the user having to wait on the server to call a whole new page of HTML, Ajax allows these page transitions to happen almost without the users knowledge. When a user triggers a certain event, Ajax sends a request to the server to run the required event and then receives the response from the server a few seconds later. Without Ajax, when an event like this is triggered the server has to take the request from the user, gather the data entered, run it through an entirely new form and then send the data back to the user as a completely new page. Ajax bypasses this annoyance by running the request in the background without the users knowledge. Instead of sending the request directly to the server Ajax runs the request through some separate JavaScript code that figures out what to do with the request and sends it to the server. The server then receives the request from the JavaScript and instead of calling a whole new page sends it back to the JavaScript code, where it is then run in whatever way the programmer told it to. Meanwhile the user has been scrolling around the page and doing other things without even knowing that they sent a request.


The XMLHttpRequest Object:

Remember when I talked about that piece of JavaScript that sends and receives information from the server? That's the XMLHttpRequest object. Luckily, all we have to do is create a new XMLHttpRequest object and it does all the work for us!

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

	var requestObject = new XMLHttpRequest();
	
</script>

Pretty simple right? All we did was create a new variable request and set it equal to a new XMLHttpRequest object! Unfortunately it's not as simple as that. XMLHttpRequest works with FireFox Safari, Google and Opera browsers, but for some strange reason Microsoft based browsers(Internet Explorer) have their own version of the XMLHttpRequest object, in fact they have two versions of it! So what if I wanted to make my Ajax application support all browser types? The solution is somewhat complicated:

<html>
<head>
<script language = "javascript" type = "text/javascript">
	//add this instead of var request = new XMLHttpRequest();
	var requestObject = false;
		try{
			requestObject = new XMLHttpRequest();
		}catch(tryIE){
			try{
				requestObject = new ActiveXObject("Msxml2.XMLHTTP");
			}catch(tryIE2) {
				try{
					requestObject = new ActiveXObject("Microsoft.XMLHTTP");
				}catch(typewriter){
					requestObject = false;
				}
			}
		}
</script>
</head>
</html>
//This should be saved as an HTML file.

This code is the easiest way to set up an XMLHttpRequest object that's compatible with all browsers. We start out by setting the variable request to false and then try to set it up as a new XMLHttpRequest object. If this doesn't work because the user is on a microsoft browser(catch(trymicrosoft)) we tell request to try and make itself a new Microsoft specific XMLHttpRequest object. If this doesn't work(most likely because the user is using an outdated version of Internet Explorer) we attempt to setup request as the second Microsoft specific XMLHttpRequest object. Finally if that doesn't work(most likely because the user is attempting to access your Ajax application with a freaking typewriter) we set request equal to false, disabling the XMLHttpRequest object.


Making the Input:

In order to have Ajax send a request to the XMLHttpRequest object we first need to have something trigger Ajax sending the request. In our case this will be a text input box that when the users enter his or her phone number the page send an alert telling them what they put into the box. The input box is easily created in HTML like so:

<html>
<head>
//add this
<p>Please enter your phone number:</p>
<input type="text" size="14" name="number" id="number" />

<script language = "javascript" type = "text/javascript">
	
	var requestObject = false;
		try{
			requestObject = new XMLHttpRequest();
		}catch(tryIE){
			try{
				requestObject = new ActiveXObject("Msxml2.XMLHTTP");
			}catch(tryIE2) {
				try{
					requestObject = new ActiveXObject("Microsoft.XMLHTTP");
				}catch(typewriter){
					requestObject = false;
				}
			}
		}
</script>
</head>
</html>

This should give you an input box that allows you to input numbers and letters that don't really do anything yet.


Sending the Request:

So now we have an input box that allows us to type things. Pretty cool but not exactly anything new or exciting. Well it turns out this input box is going to be the way our Ajax application functions. Users will type in a number and when they hit enter Ajax will send a request to the server through our XMLHttpRequest object like I explained earlier. Unfortunately this won't just magically happen. In order for Ajax to know that we want it to send a request when the users enters some text we have to do this:

<html>
<head>

<p>Please enter your phone number:</p>
<input type="text" size="14" name="number" id="number" />

<script language = "javascript" type = "text/javascript">
	
	var requestObject = false;
		try{
			requestObject = new XMLHttpRequest();
		}catch(tryIE){
			try{
				requestObject = new ActiveXObject("Msxml2.XMLHTTP");
			}catch(tryIE2) {
				try{
					requestObject = new ActiveXObject("Microsoft.XMLHTTP");
				}catch(typewriter){
					requestObject = false;
				}
			}
		}
		//add this
	if (!requestObject)
		alert("Error we could not send your request!");
	function getNumber() {
		var number = document.getElementById("number").value;
		var url = "/~benm/newdev/Arraytutorialtester.php?number=" + escape(number);
		requestObject.open("GET", url, true);
		requestObject.onreadystatechange = update;
		requestObject.send(null);
	}
</script>
</head>
</html>

This part is a little confusing so lets go through it part by part. First we say if request isn't true then an alert pops up on the users screen saying that there was an error in sending the request. Next we declare a new function called getNumber and get the value of the element "number". Next we declare the url of the PHP page that holds the information and value for our number element, this url depends on where you're going to place your PHP file. This url is where my PHP file is located and if the url is wrong the Ajax request will come up blank and not give us anything when we finally get around to receiving the information from the server. Next the open function opens a connection to the server the "GET" has to do with our PHP and is the way we will connect to the server, other ways include POST and HEAD. Next is the url we are going to connect to. The last part tells the server that the request should be asynchronous indicating Ajax. Next we wrote the onreadystatechange which tells the server to run a function update(which we have yet to create) when it's finished running through the request. Without this the server would merely run through the request and then throw it away as it had no idea what to do with it. The last part send(null), sends null because we've already told the server what we're sending it in our url.


The Update Function:

Remember how I talked about onreadystatechange and how it called a function update? Well we haven't told the server what the function update does yet. At this point the server reaches that piece of code, shrugs it's shoulders and decides not to do anything. Let's remedy this by adding the following to the bottom of our code:,

<html>
<head>

<p>Please enter your number:</p>
<input type="text" size="14" name="number" id="number" />

<script language = "javascript" type = "text/javascript">
	
	var requestObject = false;
		try{
			requestObject = new XMLHttpRequest();
		}catch(tryIE){
			try{
				requestObject = new ActiveXObject("Msxml2.XMLHTTP");
			}catch(tryIE2) {
				try{
					requestObject = new ActiveXObject("Microsoft.XMLHTTP");
				}catch(typewriter){
					requestObject = false;
				}
			}
		}
		
	if (!requestObject)
		alert("Error we could not send your request!");
	function getNumber() {
		var number = document.getElementById("number").value;
		var url = "/~benm/newdev/Arraytutorialtester.php?number=" + escape(number);
		requestObject.open("GET", url, true);
		requestObject.onreadystatechange = update;
		requestObject.send(null);
	}
	//add this
	function update() {
		if (requestObject.readyState == 4){
			if(requestObject.status == 200){
				alert(requestObject.responseText + "");
			}else if(requestObject.status == 404){
				alert("Could not find URL");
			}else if(requestObject.status == 403){
				alert("Requested URL is forbidden");
			}else
			alert("Status is " + request.status);
		}
	}
</script>
</head>
</html>

As you can see this part is pretty complicated so let me explain it part by part. First after we declare what the function is and make an if statement. It's a pretty normal if statement except for whats inside of it. What the heck is readyState == 4? Server's have 4 ready states. 1 being once the request is prepared but has not yet been sent. 2 is when the request has been sent and the server is processing it. 3 is when the server is processing the request and has some of the data but hasn't completely finished processing the request, and 4 is when the server has finished processing the request and is ready to return the data to the user. So this if statement says: Once the server is completely finished processing then run the next if statement. The next few parts have to do with status codes. Have you ever attempted to search for a certain webpage and you type in the URL wrong and a message pops up saying Error Status: 404 page not found or something of the sort? Well These are status codes. A status code of 200 means that everything is okay, so our second if statement is saying "If everything checks out okay then alert the responseText(the value returned from the URL). These first two if statements combine to make sure that the server is completely ready and that everything has checked out okay before alerting the value of the URL. The next few else if statement are simply different status codes indicating different things. The first is 404 not found that I talked about earlier. The second is the 403 status code meaning exactly what it says in quotes, the requested URL is forbidden. The else statement deals with anything that isn't a 200, 404 or 403 status by alerting what the status is if it isn't one of the three described.


Writing the PHP:

Now that we have our Ajax application complete we need to write the PHP to get the Ajax to work. The PHP itself is quite simple especially if you have just completed the PHP tutorials on this site. Before you begin writing PHP do you remember that URL we wrote? You'll want to place this new PHP file at the location of the URL you wrote and where I wrote Arraytutorialtester.php you should write the name that you gave your new php file. Once you have that complete, let's get to writing some PHP!

<?php
	if(ctype_alpha($_GET["number"])){
		echo "I'm sorry you wrote a bunch of stupid letters instead of a number you jerk!";
	}else{
		echo "Your number is:" . ($_GET["number"]);
	}
?>

This is pretty simple PHP except for a few things. ctype_alpha() checks to see if all of the characters in a string are letters. In this case it's checking to see if all of the characters in the string ($_GET["number])(the value the user put into the input box) are letters and if they are it tells them their a jerk and ruins their hopes and dreams! The $_GET function gets(hence the name) the value of "number"(in this case the value of the input box) from our html page that it's linked to.


Making it all Work:

Right now if you enter text into the input space and hit enter nothing will happen. This is because we've forgot the most important part! Right now when we hit enter after changing the text we're not telling the server to do anything. All we have to do to change this is add one little line to our input button:

<input type="text" size="14" name="number" id="number" //addition goes here: onChange = getNumber() />

This tells Ajax that when a change occurs inside the input to run our getNumber function. Now when you type some numbers into the input and hit enter an alert will pop up telling you the value of the number's you entered!

I hope you've enjoyed this tutorial on Ajax, feel free to look around at some of the other tutorials on PHP if you haven't already. If you want to see a working version of what we created in this tutorial feel free to visit this link: Ajax number returner.