Skip to content

Building your first Ajax application with PHP

Peter's WebDev Workshop

Find this tutorial useful?





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]




First ever Ajax application with PHP


Name:  




[/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]

Name:  



[/html]

Notice that above, I call doAjaxQuery with one parameter, the URL to send the data. This is simply ajax.php, plus the query mark ?, then name=. After this, we ask JavaScript to get the value of the name field and stick it at the end of the URL.

So if we enter Bob as the name, the URL JavaScript would query would be ajax.php?name=Bob (filling in the name for us).

OK at this point your script should work, so try it out with both the names in the list and some random names too to make sure it comes out with the right response.

(If you’re having trouble, download the completed files that I’ve tested that work below).

Looking in the internals

So let’s just recap exactly what happens from the point of view of the first page.

  • The user loads the first page and enters a name into the box called name.
  • The user submits the form, which kicks doAjaxQuery into action.
  • doAjaxQuery sets up an Ajax request and submits it (to a URL containing the contents of name).
  • We wait until ajaxObject.readyState is equal to 4.
  • ajax.php responds and checks to see if the contents of name it has been given is in the list.
  • If there is a match, PHP responds 1, otherwise 0.
  • JavaScript takes this response and displays an appropriate message.

We’re done (almost)

Wow, that’s done! If you followed this correctly, you should now have a very simple Ajax application! Armed with this knowledge you should now be able to adapt this code to do something maybe a bit more complex. In fact, you can do quite a lot without even touching XML.

In a future tutorial, I’ll be looking at parsing XML with JavaScript, so we can do more complicated actions with the responses sent by our server. We’ll be looking at building our own XML tags to inform JavaScript of what exactly is going and transmit a bit more information between Ajax requests.

If you want a copy of the completed script, download the files below.

Download .tar.bz2 | Download .zip

Homework

If you feel like exploring a bit more, you could try doing these things:

  • Create a div and instead of popping an alert box, place the message inside that div.
  • Add a box for age and also use ajax.php to check that age is within a range of acceptable ages. Use another value (2 for example) to indicate this check has failed. Modify the JavaScript to display an appropriate message.
  • Change the script to do something completely different!

Resources

For the upcoming JavaScript-heavy tutorials, I’d seriously recommend investing in a developer browser plugin.

If you’re a Firefox user, try FireBug. It’s free of course, and not only does it feature a great JavaScript debugger, but a CSS and DOM inspector and the ability to spy on Ajax requests (useful for debugging your Ajax applications).

If you’re not on Firefox, unfortuantely I don’t have any links, but post your favourite developer plugins for the rest (and FF ones too) in the comments.

Feedback feedback feedback!1/2 hours to do the main part of this tutorial, so really, any feedback is really appreciated. If this helped you, please drop a comment as it keeps me motivated to write more!

Equally, if you’ve had problems getting my code to work, comment and I’ll see if I can help you out.

Heh, thanks for reading this far(!)

UPDATE: Ready to take Ajax further? I’ve got a followup tutorial.

Icon from Oxygen icon set, CC BY-NC 2.5.

Find this tutorial useful?





Like this post?

If you would like to support the time and effort I have put into my tutorials and writing, please consider making a donation.

28 Comments

  1. Leonid Prokopets wrote:

    The example did not work on Firefox/1.5.0.9 till I changed line

    on

    So “document.getElementById(‘name’).value)” does not seem to work properly on FireFox.

    Thursday, January 4, 2007 at 18:41 | Permalink |
  2. Peter wrote:

    Unfortunately, WordPress has (for good reasons) removed the script tags from your comment so I can’t see what you really wanted to say.

    Feel free to drop me an email with the relevant info, or try posting the offending code again omitting the script tags (or manually escaping them if you know how).

    If you get in touch again, I’ll see if I can take a look at the problem. For the record, it works fine for me on Firefox 2.0.0.1 – but I will investigate if you can get me the code.

    Thursday, January 4, 2007 at 22:11 | Permalink |
  3. Lee wrote:

    Thanks load’s for this tutorial.
    Ajax is something that I’ve been wanting to learn for a while, I downloaded it earlier and was about to ignore it, the amount of javascript just seemed too much.
    But after a couple of minutes of altering the code I was able to integrate it easily into a current project!

    Thanks again

    Lee 🙂

    Saturday, February 17, 2007 at 23:35 | Permalink |
  4. Hi Peter,

    Thanks for the effort put into this. It is the easiest introduction to AJAX and PHP I have found.

    I couldn’t get the downloads to work, but copying the code and creating the pages was easy enough.

    Onto the more advanced tutorial tomorrow ;-).

    Thanks

    Andrew

    Wednesday, June 27, 2007 at 13:37 | Permalink |
  5. Peter wrote:

    Thanks for letting me know about the download links – there was some old stuff lying around from my old domain that was breaking it.

    They are fixed now. Thanks for your compliments too! 😀

    Wednesday, June 27, 2007 at 18:39 | Permalink |
  6. Alan Gilmore wrote:

    Thanks for this series of tutorials. I am a programmer of 13 years trying to add ajax and php to my skills. The problem is that all the books and tutorials I have seen treat javascript like neat trick provider instead of an OOP language like I’m used to. Keep up the good work, I’ll be back.

    Alan

    Friday, October 17, 2008 at 14:08 | Permalink |
  7. badpenguin wrote:

    I can see absolutely no purpose for the session_start() in your ajax.php, other than to waste resources.

    Friday, October 17, 2008 at 20:43 | Permalink |
  8. kaizened wrote:

    Many thanks for giving me a first experience with AJAX. I think the way you make tutorials is the best there is for starters like me.
    I noticed one error:
    if (ajaxObject.responseText == ‘1’) {
    should become
    if (ajaxObject.responseText == 1) {
    because in my browser the number was recognized and not the string

    Saturday, October 18, 2008 at 00:10 | Permalink |
  9. Chris wrote:

    Really good simple tutorial, and well explained, so just a small question!

    Could you just explain why the form submit parameter is action=”javascript:” and the ajax is called by the onsubmit event?
    I was thinking the onsbmit parameter could be the form action, but I tried and it doesn’t work, i just don’t understand quite why!
    Thanks

    Saturday, October 18, 2008 at 19:01 | Permalink |
  10. Peter wrote:

    @Chris

    From what I remember, it is certainly possible to put doAjaxQuery() inside the action of the form, provided you prefix it with javascript:

    Something like this:

    action="javascript:doAjaxQuery(...etc...)"

    However, it seemed to me at the time to be ‘cleaner’ to put JavaScript code into the onsubmit event handler, as that’s what event handlers are designed for (and you don’t need the javascript: prefix there).

    The blank javascript:; in the action therefore is simply to prevent the browser from going anywhere when the form is submitted, but to ensure that the onsubmit event code is still executed.

    Saturday, October 18, 2008 at 23:18 | Permalink |
  11. Mario wrote:

    Excellent tutorial for starters, thanks!

    Mario

    Tuesday, October 21, 2008 at 19:04 | Permalink |
  12. Sean wrote:

    Hi, I really dig this tutorial; it’s the first one I’ve been able to get my head around. I have one question, though…

    You check if readystate equals 4, but at the closing of that if structure, you say if it isn’t 4, wait until it is. If the readystate does not yet equal 4, how do you return to the top of the function? I would think you would need to have something like while readystate not equal to 4…

    What am I missing?

    Thanks again!

    Thursday, February 26, 2009 at 05:02 | Permalink |
  13. Peter wrote:

    Sean,

    ajaxResponse() is called automatically for us each time the readyState of ajaxObject changes (we asked it to do this by saying ajaxObject.onreadystatechange = ajaxResponse).

    So when we enter that function, we check to see if the readyState is what we want it to be. If it isn’t, we just ignore the rest of the function and don’t do anything. As soon as the readyState changes a second time, the function is called again automatically.

    So, say the readyState changes to 2 (meaning we’re still waiting for the data back from the server). Because it has changed, ajaxResponse is called. ajaxResponse checks if it equals 4; it doesn’t, so we do nothing and the function ends.

    If the readyState then changes to 4, ajaxResponse is called again, it is equal to 4, so we go and do the processing.

    Thursday, February 26, 2009 at 09:46 | Permalink |
  14. Jon wrote:

    Thank you for a clear and concise introduction to Ajax and by extension Javascript I found it very helpful in developing my extremely basic knowledge of this subject, it is something I want to add to my website which is a basic XHtml/PHP/MySQL offering, I am hoping to use the spry framework in certain sections but, I find that it helps to have some basic Javascript knowledge to start with, which brought me here, keep up the great work

    Thursday, June 4, 2009 at 18:07 | Permalink |
  15. mayank wrote:

    great tutorial bro…for the starters……keep doing it

    Monday, August 10, 2009 at 02:40 | Permalink |
  16. Keith Murphy wrote:

    Thanks for a great tutorial! This is an elegant example, and makes a great way to start with AJAX for PHP.

    Thanks,
    Keith

    Tuesday, September 22, 2009 at 21:36 | Permalink |
  17. Samantha Crane wrote:

    Many thanks for your time and effort, that’s a great help. Can’t quite do what I want yet, but this is a good first step.

    Tuesday, October 6, 2009 at 17:42 | Permalink |
  18. John wrote:

    Thank you for the tutorial, which help me a lot.
    Really thank you.

    Monday, November 2, 2009 at 05:47 | Permalink |
  19. Sophia wrote:

    Thank you for this tutorial. I’ve been looking around for the web for a concise, straightforward tutorial.

    Friday, January 29, 2010 at 17:45 | Permalink |
  20. Steven wrote:

    Thank you for the tutorial. I particularly enjoyed your use of language – ‘plonk in a tag’, I appreciate the heavy use of comments in your code and am happy to say your code from the download.zip works on my laptop.

    Monday, April 5, 2010 at 10:05 | Permalink |
  21. exos wrote:

    Nice tutorial!! thx a lot, I’ve understood how it works!!!!!!!!!!!!!!!!!!!

    Tuesday, September 7, 2010 at 09:08 | Permalink |
  22. muhammad ali wrote:

    Hi
    This made a big contribution from your side to me
    thnx

    Saturday, April 16, 2011 at 13:34 | Permalink |
  23. Hammad Tariq wrote:

    Thanks a lot for such useful post/tutorial. You made it look very simple and easy.

    regards

    Sunday, May 6, 2012 at 09:47 | Permalink |
  24. Michael wrote:

    Great tut. Not hard at all to understand. I have one question about readyState. Why does readyState need to equal 4 and not like 10 or 3 or 120? I don’t understand this at all. Any clarification would be great. Thanks

    Wednesday, October 3, 2012 at 23:59 | Permalink |
  25. Peter wrote:

    Michael,

    The readyState number has four possible valuesuninitialized, loading, interactive and complete. Each of these are numbered 1-4.

    Because we don’t want to do anything until the Ajax loading of the document is complete, we wait for readyState number 4.

    Hope this helps make it clear!

    Monday, October 15, 2012 at 07:15 | Permalink |
  26. Jesse wrote:

    Thank you Peter for taking a complex concept and breaking it down into very understandable pieces that anybody can learn and build on. I really appreciate it.

    Monday, October 15, 2012 at 19:14 | Permalink |
  27. umair wrote:

    after reading and watching many pages and videos about ajax. finally I found your tutorial. it’s very easy and helpful.

    Thanks for your time to write helpful material for ajax learners.

    Tuesday, September 3, 2013 at 07:26 | Permalink |
  28. Mustafa Amiri wrote:

    Dear Sir,
    It was really help full article, Kindly recheck this part of the code:

    if (ajaxObject.responseText == ‘1’) { // if the result is 1

    alert(‘Welcome back!’);

    I believe it should be
    if (ajaxObject.responseText == 1) { // if the result is 1

    alert(‘Welcome back!’);

    Remove the single quote from the number value.

    Thanks;
    Wish you all the best

    Monday, March 10, 2014 at 06:05 | Permalink |

28 Trackbacks/Pingbacks

  1. Taking Ajax further with PHP « Blog « Peter Upfold on Monday, August 4, 2008 at 16:23

    […] this series, and it’s been more than that since I last looked at Ajax in PHP. OK, I might admit it, it was this comment that motivated me to pick up this series again. Oh, that and I’m now on the half term break, so I’m […]

  2. 50 Excellent AJAX Tutorials | Tutorials | Smashing Magazine on Thursday, October 16, 2008 at 22:45

    […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX. […]

  3. Useful AJAX Tutorials | Neurosoftware web dev on Friday, October 17, 2008 at 07:57

    […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX. […]

  4. pligg.com on Friday, October 17, 2008 at 12:10

    Building your first Ajax application with PHP…

    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…

  5. 50 Excellent AJAX Tutorials | POLPDESIGN on Saturday, October 18, 2008 at 08:12

    […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX. […]

  6. 50 Excellent AJAX Tutorials | Web Burning Blog on Saturday, October 18, 2008 at 09:05

    […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX. […]

  7. […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX. […]

  8. 50 Excellent AJAX Tutorials | Evolution : weblog on Friday, October 31, 2008 at 05:22

    […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX. […]

  9. 50 Excellent AJAX Tutorials « Rohit Dubal on Monday, February 16, 2009 at 10:36

    […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX. […]

  10. […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX. […]

  11. […] Building Your First AJAX Application with PHP – This is a tutorial for beginners that show the ways in getting started with PHP. […]

  12. AJAX – En guide nära dig | Real Blogg on Sunday, September 6, 2009 at 14:09

    […] Bygg din första AJAX applikation […]

  13. […] Building Your First AJAX Application with PHP An introductory post for getting started with AJAX […]

  14. […] 12. Building your first Ajax application with PHP […]

  15. 30 AJAX Tutorials For Web Developers, Anyone! « Web Design on Thursday, February 11, 2010 at 20:40

    […] 12. Building your first Ajax application with PHP […]

Post a Comment

On some sites, you must be logged in to post a comment. This is not the case on this site.
Your email address is not made public or shared. Required fields are marked with *.
*
*
*

Posting a comment signifies you accept the privacy policy.
Please note — your comment will not appear straight away, as all comments are held for approval.