Simple AJAX Demo

This AJAX demo shows a very basic example of how the AJAX script could be used. Click the test button below and the contents of a file called 'helloworld.txt' will be retrieved and displayed it in an alert box.

To get the AJAX script used in this example go to the AJAX tutorial..

You can see an example that sends data to the server and updates the page at the AJAX Demo App page.

To see an example that uses an XML response to update the page check out the XML AJAX Demo.

How it works

For this demo to work the first thing we need to do is include the AJAX script.

<script type="text/javascript" src='ajax.js'></script>

Because the AJAX script does all the hard work sending the AJAX request and handling the response is incredibly simple. Below you'll see the code for the ajaxTest function.

function ajaxTest() { function responseHandler(ajaxRequest) { alert(ajaxRequest.responseText); } ajaxSend('get', 'helloworld.txt', '', responseHandler); }

The ajaxTest function first defines a function that will handle the response. This responseHandler function will be passed the ajaxRequest as it's only parameter. The responseHandler is very simple, it just displays the responseText of the request in an alert box.

After defining the responseHandler the test function then sends the request. The parameters used by the ajaxSend function define the following.

  1. The request method ('get').
  2. The url the request will be sent to ('helloworld.txt').
  3. The request parameters (''). For this example we don't need any so we just pass an empty string.
  4. The function that will handle the response (responseHandler).

The code for the button that calls ajaxTest is...

<button onclick='ajaxTest();'>AJAX Test</button>

That's all you need to use AJAX get the contents of any file. A common use is to retrieve a snippet of HTML will be retrieved and add it to the page.

Using XML

Once you've got this technique down the next step is to look at handing back XML documents in response to your requests. This has the advantage of providing a structured way of handling the data, meaning that multiple applications could retrieve the same XML file and handle it in there own way.

Check out the XML Ajax Demo for an example.


If you've got any questions or feedback about this article please post them in the Dynamic Tools Javascript Forum.