On the heels of two very successful tutorials on creating a collapsible div and an animated sliding div, I’ve decided to write another. It seems my last few helped a number of programmers learn a simple trick, and hopefully this one will do the same.
Note, I’ve also upgraded to a much newer, faster server, so hopefully the social networking sites won’t “collapse my server” again, as one Digger so eloquently put it.
Hearing about AJAX constantly, but never have found time to read a lengthy, frustrating, complex tutorial? In the following post, I’m going to explain how to add AJAX functionality to your website in three easy steps. It’s actually quite simple, and I’m going to try and be clear and to the point, but not over or under-explain anything like most tutorials have a tendency to do.
Before you begin, decide what purpose or additional functionality adding AJAX to your website will accomplish. Will it be a live search feature? Something to save user preferences? In this example, we’re developing a simple calculator. Let’s dive in.
Step 1: Create the Intelligence
First let’s make the brain of the system. In our calculator, we’re going to need a PHP function to actually perform the operations. We’ll handle the front-end later, but for this file, we’ll take our input from GET request strings (variables passed through the URL itself, such as file.php?var=value&var2=test).
Name this file: backend.php if($_GET['op']=="" || $_GET['num1']=="" || $_GET['num2']==""){
echo "Error: Please complete all fields.";
exit;
}
if($_GET['op'] == "divide" && $_GET['num2'] == "0"){
echo "Error: Division by zero.";
exit;
}
if(!is_numeric($_GET['num1']) || !is_numeric($_GET['num2'])){
echo "Error: Invalid numbers.";
exit;
}
switch($_GET['op']){
case "add":
echo $_GET['num1'] + $_GET['num2'];
break;
case "subtract":
echo $_GET['num1'] - $_GET['num2'];
break;
case "multiply":
echo $_GET['num1'] * $_GET['num2'];
break;
case "divide":
echo $_GET['num1'] / $_GET['num2'];
break;
}
?>
Now, let’s take a look at this file. We’re working with three variables passed from the GET string: the operation such as add/subtract/divide/multiple ($_GET[’op’]), and the two numbers we’re performing the math on ($_GET[’num1′] and $_GET[’num2′]). For example, we might call this page like this: backend.php?op=add&num1=12&num2=4 . This is running our above file (backend.php), passing “add” as the ‘op’ variable, and 12 and 4 as the two numbers.
The first four lines of the above backend.php script checks to make sure all the variables were entered. If any of the three values are blank (”"), then it errors and exits. The next if-block is checking for a divide by zero error. If the op variable is divide and the num2 variable is zero, it errors and exits. Simple.
Next it checks to ensure you entered valid numbers with the is_numeric() function in PHP. If you enter a letter or something else in the field, it will show and error and exit.
The next (and last) block we get to is the switch statement. This goes through and checks the op variable to see what we’re trying to do here. Every case-statement represents one of the possible operations (add/subtract/divide/multiply). When it figures out which operation is being requested, it performs the math on num1 and num2, echo’s the result, and breaks out of the switch statement, thus ending the file. If you need to brushen up on how switch statements work, php.net has a great tutorial.
There, now you’re 1/3rd done with adding interactive AJAX functionality to your web application. Easy right?
Step 2: Create the Form
Now we’re going to create the frontend to the AJAX. This is the part the user sees, and is mostly basic HTML. You can add this to any PHP or HTML file you have, anywhere you want.
Here’s the frontend code for our calculator:
This is simple HTML, adding two textboxes, a drop-down (with values corresponding to the values of the case statement in backend.php), a button, and a DIV. Notice I’m not using a submit button (it doesn’t matter) because I’m not using a form. This might not be best practice, but it goes to show you’re not submitting anything to another page, like you traditionally would. The button has a function “doMath()” which is called from the onClick attribute. We’ll explain this function in step 3, but for now, just know that begins the AJAX and solves the math problem. Also notice we’re using id’s instead of names for the textboxes and drop-down field (select)- this is for us to reference the fields from Javascript in the next step. The last line is a simple DIV with a bit of CSS styling (display: inline makes it appear after the equals button, rather than on it’s own line, and the font size is for aesthetics). We set the id of this div to “answer”, and we’ll be using it later from the Javascript to output the answer.
Very easy. Now we have the backend setup to do the math, and the frontend to ask the user what kind of math he wants to do… so now the only piece left is connecting them together!
Step 3: Connecting the Frontend and Backend Together
This step is the trickiest, but stick with me, and you’ll see how easy it really is. We use Javascript (AJAX = Asynchronous Javascript and XML) to talk between the HTML and the PHP.
For this step, let’s create another new file, and call it ajax.js.
http = getHTTPObject();
function getHTTPObject(){
var xmlhttp;
/*@cc_on
@if (@_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
@else
xmlhttp = false;
@end @*/
if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = false;
}
}
return xmlhttp;
}
function doMath(){
var url = "backend.php?op=" + document.getElementById('op').value;
url += "&num1=" + document.getElementById('num1').value;
url += "&num2=" + document.getElementById('num2').value;
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse(){
if(http.readyState == 4){
document.getElementById('answer').innerHTML = http.responseText;
}
}
Now, your first reaction might be to panic, but stay calm, it’s not that bad. The entire getHTTPObject() function (half the file) you do not need to understand. It’s a standard function included in almost every AJAX script out there… simply copy and past that exactly as it is, and forget about it. There, now you’re just left with the first line, the doMath() function, and a small function called handleHttpResponse.
The first line is declaring an object to ask PHP for it’s result. Think of it as a mini web browser.
The doMath() function is where you actually send the AJAX request. Remember it being called when you click that button in the frontend? This is what’s run. The first three lines of this function are building a variable (url) that is the PHP page we’re going to request. It begins with “backend.php?op=” and grabs the value of the drop-down from the frontend to find out if we’re adding, subtracting, multiplying, or dividing. Then it adds the two numbers from the frontend on to the end of URL request string as well, using document.getElementById to find them (the textboxes’ values). Now the url variable is left with something similar to the example I gave right after the code in step 1. You could in theory plug this URL into your web browser, and see the result yourself, but instead we’ll let Javascript do it for us. The last three lines of the doMath() function pass that URL to our mini web browser (variable “http”), and essentially press the Go button. It sends the request, and tells it to notify us when it gets a response back, via the handleHttpResponse() function.
Now, the last function of our Javascript file is the handleHttpResponse() function… called automatically by our mini web browser when our PHP page finishes downloading (and it has an answer). The if-statement is basically saying “if the PHP site is done loading and you have an answer, continue.” The middle line is a call to set the innerHTML property of the answer DIV on the frontend to whatever the PHP page says…. in our case… the math answer.
Important!
Now, for this to work, you need to call the ajax.js file from the file where your frontend is. This is done by simply placing this line above the frontend somewhere in the code:
The best place to put this is between the HEAD tags of the file, but anywhere would work. If you do not add this line, your website will give errors when someone tries the AJAX, and it won’t work.
And you’re done!
Now, I’m sure critics are going to ask why do this with AJAX when I could easily accomplish the same thing with pure Javascript, and the answer is this is a tutorial to learn. Often times the PHP backend does MySQL calls, or things that Javascript couldn’t do. For example, live searches (results below the textbox as you type) are this same basic framework, but the backend searches a database for what the user is typing, and returns the results to set in the answer div (equivalent). Simple!
And as always, here is a live, working demonstration of the tutorial in action:
I enjoy your comments and requests for future tutorials!
1 commento:
Today, I went to the beach front with my kids. I found a
sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She put the shell to her ear and
screamed. There was a hermit crab inside and it pinched her ear.
She never wants to go back! LoL I know this is entirely off topic but I
had to tell someone!
Here is my homepage; sizzling hot download
Posta un commento