Greetings and welcome to an all-new tutorial series, Peter’s Webdev Workshop. This tutorial series will focus on web development, mainly focusing on using PHP as a server-side language, but I’m not ruling out having a crack at Python or Ruby, ASP.NET/Mono C# or something like that. This series will also look at JavaScript on the client side and we’ll be using XHTML for all the markup.
Before I jump into today’s topic, there’s a bit of admin and introduction I need to do to start up the new series. See you after the jump!
All the code examples I use in this series will be released under the Modified BSD Licence (unless I mention otherwise), meaning that you’re free to take the code examples, modify them and/or use them in your application, whether open or closed source, provided you mention me (there are a couple of other minor things too). Of course if you get inspired by my code and write something equivalent that does the same job, you can do what you want with it, it’s yours. For reference, you can read the whole licence here.
Unlike Beginner’s Linux, this series will expect you to be familiar with (X)HTML and to have some basic skills with PHP and some JavaScript knowledge. I won’t start with too difficult things and as this series evolves we’ll probably see some introductions and other groundwork.
This tutorial, however, throws you in at the level of building your first ever Ajax application in PHP. So for this one, you need a working knowledge of PHP and a good grasp of programming basics.
Ajax – isn’t that some kind of cleaner?
No, not that Ajax. Ajax, or Asynchronous JavaScript and XML, is a new web technology that allows you, basically, to utilise JavaScript to get data from a server without reloading the whole webpage. This comes in handy for many things and is powering all of the new ‘rich web applications’ that are popping up now (Google Maps, Y!Mail Beta, Writely/Zoho Writer).
Basically Ajax means you can have elements of the page dynamically loaded without a page reload (asynchronously to the reloading), meaning you can update elements of the page without receiving the whole page again and without affecting the rest of the page. The XML part comes in when you get data from the server in XML format, then use JavaScript to parse that XML and do something useful with it.
Ajax works with any server-side technology, including PHP, Perl, ASP(.NET), Python, Ruby, ColdFusion, SSI, JSP… you get the idea, anything. We’ll of course be using PHP.
Please support this work!
There used to be advertising here, but I no longer feel sure that advertising delivers the best experience and truly reflects the values of this site.
Keeping things running, however, is not without financial cost. If you would like to support the time and effort I have put into my tutorials and writing, please
consider making a donation.
Right, so how do I start?
For this demo, we’re going to keep it simple and have two files. index.php is our main file that is loaded in the normal way by the user, and ajax.php is the script that JavaScript will call and will deliver some information.
So what are we actually going to do? Well, let’s break it down:
- index.php will contain a form where the user can enter their name.
- When submitted, the form will talk to ajax.php and determine whether that name is in a predefined list.
- If it is, we will say ‘Welcome back’. If not, we will say ‘Nice to meet you, stranger!’.
Now this isn’t particularly groundbreaking. If you wanted, you could do it in JavaScript alone, but that’s not the point. Once you know how to do this, you can adapt this to do something a bit more interesting.
Building the form
This is textbook stuff here, we’ll just build a form with one textbox and one submit button (we’ll add the JavaScript later).
[html]
[/html]
Building the backend
OK, so now we have our basic form, let’s build ajax.php, which will check for the name they entered in a list of names. We won’t do any fancy XML for now, we’ll simply return 1 if the name is in the list and 0 if it isn’t.
[php]
[/php]
So let’s just test it first without the Ajax. Put these files in a web-accessible place, and then pop open your favourite browser and go to (if you’re running a local Apache/IIS server) http://localhost/wherever/you/put/it/ajax.php?name=Bob. You should simply receive a 1 in response, which is correct.
Now try it with something random, to test the 0. Navigate to http://localhost/wherever/you/put/it/ajax.php?name=sdnjshduhwhwed and you should receive a 0. Good!
JavaScript time!
Now we need to write the JavaScript that will run this request when the user clicks the button and will interpret the 1 or 0 response to display a particular message.
Just a word of warning – Ajax is cool and everything, but do not presume all of your users have access to JavaScript and are willing to run it in their browser. In a real environment, we’d also build a fallback that doesn’t require JavaScript for users with it turned off and for people with special accessibility needs (such as those with screen readers). Don’t lock people out of your application by not providing fallback functionality.
In order to gain access to Ajax functionality, we need to initialise it in the user’s browser. There are two ways of doing this. For most (good) browsers, we use a built-in thing called XMLHttpRequest and for Internet Explorer 6/5.5 and below, we need to create an ActiveX control which does the same thing.
Once we’ve enabled this, we then send the request off to ajax.php and wait for a response. This Ajax object we’ve created has something called readyState attached to it. I won’t go through all the possibilities, but once the readyState is 4, we’re ready to rock.
So we build a little function which is run every time the readyState changes. That checks whether it’s 4 yet or not. If it is, we do the relevant processing with the information. If not, we don’t do anything and wait until the readyState changes again.
OK, so here is a basic shell of the JavaScript we will add in a minute to index.php (in fact it could be index.html, as it doesn’t have any PHP in it!). Plonk this in a <script> tag in the head of your page.
If this all looks a bit scary (maybe you haven’t done much JavaScript before), the vital thing is do not panic and don’t give up yet. For now, if you’re not confident, simply copy my code exactly and as you begin to explore it, you will be able to edit it to your needs.
[js]var ajaxObject = false;
// this is our object which gives us access
// to Ajax functionality
function doAjaxQuery(url) {
ajaxObject = false;
if (window.XMLHttpRequest) { // if we’re on Gecko (Firefox etc.), KHTML/WebKit (Safari/Konqueror) and IE7
ajaxObject = new XMLHttpRequest(); // create our new Ajax object
if (ajaxObject.overrideMimeType) { // older Mozilla-based browsers need some extra help
ajaxObject.overrideMimeType(‘text/xml’);
}
}
else if (window.ActiveXObject) { // and now for IE6
try {// IE6 has two methods of calling the object, typical!
ajaxObject = new ActiveXObject(“Msxml2.XMLHTTP”);
// create the ActiveX control
} catch (e) { // catch the error if creation fails
try { // try something else
ajaxObject = new ActiveXObject(“Microsoft.XMLHTTP”);
// create the ActiveX control (using older XML library)
} catch (e) {} // catch the error if creation fails
}
}
if (!ajaxObject) { // if the object doesn’t work
// for some reason it hasn’t worked, so show an error
alert(‘Sorry, your browser seems to not support this functionality.’);
return false; // exit out of this function
}
ajaxObject.onreadystatechange = ajaxResponse; // when the ready state changes, run this function
// DO NOT ADD THE () AT THE END, NO PARAMETERS ALLOWED!
ajaxObject.open(‘GET’, url, true); // open the query to the server
ajaxObject.send(null); // close the query
// and now we wait until the readystate changes, at which point
// ajaxResponse(); is executed
return true;
} // end function doAjaxQuery
function ajaxResponse() { // this function will handle the processing
// N.B. – in making your own functions like this, please note
// that you cannot have ANY PARAMETERS for this type of function!!
if (ajaxObject.readyState == 4) { // if ready state is 4 (the page is finished loading)
if (ajaxObject.status == 200) { // if the status code is 200 (everything’s OK)
// here is where we will do the processing
if (ajaxObject.responseText == ‘1’) { // if the result is 1
alert(‘Welcome back!’);
}
else { // otherwise
alert(‘Nice to meet you, stranger!’);
}
} // end if
else { // if the status code is anything else (bad news)
alert(‘There was an error. HTTP error code ‘ + ajaxObject.status.toString() + ‘.’);
return; // exit
}
} // end if
// if the ready state isn’t 4, we don’t do anything, just
// wait until it is…
} // end function ajaxResponse[/js]
As you can see, for now we simply pop up a message and don’t do anything particularly special, but that’s OK for now.
Integrating the script and the page
We need to make some minor changes to our index.php to make it JavaScript enabled. I’ll repost everything from <body> down to the bottom (you’ve added that JavaScript, right?!).
[html num=115]