AJAX Made Simple

From Webmaster-A Webmaster Resources
With just 4 simple javascript functions it is possible to use much of the magic of Ajax on your pages. No complex and mysterious toolkit or framework to learn, you can be up and running with a simple AJAX test on your server within an hour.

What is AJAX

Ajax is a method of communicating between your page and a web server in such a way that parts of your page can be refeshed dynamically without reloading the whole page. We present a simple to implement system based on Javascript and PHP to get you going and build confidence. It is possible to build a very complex Ajax site with just the functions we present here.

Uses for AJAX include:

  • Ajax Dynamic Lists - populate a list box according to the contents of some previously filled in form on a page (ie country=>town)
  • Ajax Data Retrieval - Show data from another web page selected by the user on yours
  • Ajax Images - Change Page images (ie maps,photos) according to input from user

AJAX Limitations/Problems

Because AJAX uses javascript users whose browsers do not support javascript (mobile phones mostly) will not be able to use AJAX features. If these users are important to you then use the NOSCRIPT tag to redirect them to a conventional page.

Some web hosts have a problem with AJAX implementations due to their implementation of mod_security and similar browser side firewalls. If you are struggling with trying to get the example on this page up and running then check your error logs (if you have access). If there is a line in there anything like:
[error] [client 77.99.132.28] mod_security: Access denied with code 403. Pattern match "^$" at HEADER("Content-Length") [severity "EMERGENCY"] [hostname "www.mywebsite.com"] [uri "/myajaxtest.php"]
[OLD SOLUTION - may not work!] Then you know you have this problem. To fix it on an Apache server is easy. Put your php file that you are calling from Javascript into a seperate subdirectory. Create an htaccess file with the following two lines:
SecFilterEngine Off
SecFilterScanPOST Off
and place it in the subdirectory. This will turn mod_security off just for that directory.

[Newer Fix] If you now get error 500 then you must contact your host since setting of mod security from htaccess has been disabled.

Here are our Javascript functions, these may be placed in the files head section or stored in a js file - it is up to you!

AJAX Javascript Functions

We give each seperate Ajax function on the website an action number, from 1 to whatever. We may only have one on the site or we may have 200. It does not matter. Using this technique allows us to have only one Javascript file to debug.

The first routine is getquerystring. This is a collection of action number specific lines you will have to write yourself to build the query string that will be tagged onto the php files url in POST and sent to the server. Typically a line may look like this:
if (action==1) qstr='zip='+document.addressform.zipcodetext.value;
Which would take the value of a textbox named zipcodetext in a form named addressform on the page and format it into a query string looking like 'zip=012345'. We do not have to call this routine, it is called automatically by another routine.

The next routine xmlhttpPost is the heart of our AJAX script. It takes two parameters, the URL of the php,asp, or CGI/Ruby program we wish to call on the server, plust the action number. It has a lot of stuff that is there purely to ensure that it works on all AJAX enabled browsers. It starts off by creating a new XMLHttpRequest which is the javascript object which communicates with the server side program. It opens the connection which is initialised for method POST (we could use GET but its not so secure), sends a header telling the server to expect form data, sets up updatepage to be called with the response from the server when the information is sent and finally sends the query string to the server.

xmlhttpPost will typically be called using a button, or from another javascript fragment linked to an onchange event. A button call looks like this:

Often we may want to call it automatically when something changes for example an item in a selection box is picked. This is done by using the onchange event of the control like this:

updatepage is the routine that automatically gets called by javascript when the output from your php file arrives. The variable str contains the text output from your php script (as you will see when you try the example). Once again you need to write a code fragment for each action that applies the data to your page, replacing the content of a div, or a list box, or an image, or whatever.

This is where the final function replacehtml comes in, it takes two arguments, the name of an element (a div, a select box, etc) and replaces the markup inside it with the new text. Often with list boxes it is easier to provide a full html option list (<option>Aberdeen</option><option>London</option>... <option>Swansea</option>) and replace the entire lot rather than fiddle about with Javascript addelement. Similarly if the thing you wish to change can be put in a named div then its easy to swap out the entire html contents of the div. Ok this may not be so efficient in terms of how much data is transferred but this is less of a consideration now in the broadband age than when AJAX was first created (users on slow dial-ups).

The Javascript/PHP interface in AJAX

This is really very easy. I would reccomend debugging the PHP before adding the security features we are going to talk about, and using GET instead of POST so that you can simply type in sample query strings into the navigation textbox of your browser. For example if you are testing a zip code address retrieval type script then you might type in: http://www.mysite.com/ajax/zip.php?zip=723564 or http://www.mysite.com/ajax/zip.php?zip=614582 then when you want to use it with the page you are creating remember to change from $_GET to $_POST.

It is important to remember that whatever gets sent to the screen from your php script will get sent to the AJAX script including any linefeeds, spaces and html tags. Debugging gives you a chance to tidy this up, then you know any problems must be down to your javascript implementation.

To make your PHP script secure only allow it to be executed from pages that you control. You can do this by adding an access list see below.

Simple PHP Sample Script for AJAX use

This simple test script takes a single parameter called input and creates an md5 hash from it then returns that. Its good for testing AJAX works on your hosts system. Remember to change mysite/mypage1 etc to the actual page you are calling it from. You can get the javascript from the head section of this page (using view source) and similarly the html for the form below.

Javascript/AJAX Demonstration

MD5 AJAX Demo

Type here:
MD5 Hash=

Type in your name or any string and find its md5 hash!

You are welcome to use any or all of this code. A link back would be nice!


Useful Pages

Social Bookmarking:



PHP Unique Filename Referrers

bookmark hit
...
...
vidvain.com
ozinengland.com
ecashhyip.com
www.taruhanku.com
www.google.co.in
internal hit
richardrubbra.com
www.issybizzy.com
...
www.google.com
...
www.google.dk
...
burnurfat.org
www.google.com.tr
www.build6packs.com
www.google.co.uk
www.google.it
denvang.com
thealkalinediet.org
www.dofollowtest.com
baerbykes.com
www.pressmap.de
...
www.google.com.ng
...
...
jack3d-reviews.com
...
www.google.ca
...
www.google.ie
...
beforeitsnews.com
...
www.facebook.com
theheartburn.net
...
...
www.scape-xp.com
...
www.google.co.uz

This list of people who link to this useful page is automagically maintained. Link to us, send traffic, and get listed. Simple.