New Revised CSS Library Forums Web Tools
FAQs Awards Usage Terms Contact
Categories
Other Sections
Sweet Ads
Compatibility
Bookmark online:

FF1+ IE5+ Opr8+

Basic Ajax Routine (get & post)

Author: Dynamic Drive

Description: Regardless of what you do using Ajax, they all rely on the same basic functions. This is a very small Ajax routine (less than 3 Kb) that enables you to easily use Ajax on your site to send "GET" or "POST" requests asynchronously. Some examples include getting the contents of an external HTML file, getting the contents of a XML file and return it as a DOM object, and sending information via PoST to a receiving PHP script (with the information being from either a form or any element on the page). It's easier than you think with the help of this routine! Here's a quick listing of the public variables and methods exposed by this routine:

Public Variables for use within your callback functions:
ajaxpack.ajaxobj References the current active Ajax object.
ajaxpack.filetype Returns the expected file type of the external file: "txt" or "xml."
ajaxpack.basedomain Returns the current root domain of the page, including whether the "www" prefix is present. Does NOT include the trailing slash. For example: "http://www.dynamicdrive.com"
ajaxpack.addrandomnumber (read/write) Set this to 0 or 1 (0 is default). When set to 1, a random number will be added to the end of the query string of GET requests to bust file caching of the external file in IE6. If you'll be modifying the souorce of the external file as you make Ajax requests to it, then set this variable to 1 to prevent IE6 from using the cached version of the file.

Public methods:
ajaxpack.getAjaxRequest(url, parameters, callbackfunc, filetype) Method to perform an asynchronous GET request.
ajaxpack.postAjaxRequest(url, parameters, callbackfunc, filetype) Method to perform an asynchronous POST request.

Read the documentation below for usage instructions and examples.


Directions Developer's View

To use this routine, you must add it to your page obviously. Simply insert the below script into the HEAD section of your page:

<head>
<script type="text/javascript" src="ajaxroutine.js">
/***********************************************
* Basic Ajax Routine-  Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
</script>
</head>

As you can see, the code references an external JavaScript file, which you'll need to download and copy to your web page directory: ajaxroutine.js (right click, and select "Save As"). Installation is complete.

Documentation and sample usage

With the routine added to your page, you can now perform Ajax tasks easily, such as get the contents of a text or xml file, return a XML file as a DOM object for easy parsing, or even send information from a form or arbitrary elements on the page to a receiving script such as a PHP script.

The three steps to using this routine to perform Ajax tasks are:

  1. Install the script by inserting the script in the HEAD section of your page as explained above (doh).
  2. Define a "callback" function to process the data returned by the Ajax request.
  3. Invoke the Ajax routine method to make the desired Ajax request.

Ok, all this sounds complicated, but it's actually quite straightforward.

Performing asynchronous GET requests

Using Ajax, you can perform asynchronous GET requests. Specifically, this means tasks such as: retrieve the source of an external HTML page dynamically, get the contents of a XML file as a DOM object for easy processing, or even get any data selectively returned by a server side script such as PHP that varies depending on the parameters you send to it. Lets see a basic example first:

<head>
//Step 1: Install the routine script:
<script src="text/javascript" src="ajaxroutine.js">
//CREDIT NOTICE GOES HERE
</script>
</head>

<body>

<script type="text/javascript">
//Step 2: Define a "callback" function to process the data returned by the Ajax request:
function processGetPost(){
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
if (myajax.readyState == 4){ //if request of file completed
if (myajax.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
if (myfiletype=="txt")
alert(myajax.responseText)
else
alert(myajax.responseXML)
}
}
}

//Step 3: Invoke the Ajax routine method to make the desired Ajax request.
ajaxpack.getAjaxRequest("example.htm", "", processGetPost, "txt")
</script>

Run example

As you can see, this simple example just displays the source of "exmple.htm", via the callback function "processGetPost()" that alerts the contents of a file. In Step 3, I've specified the file to get to "example.htm', and that it is a text file (non XML). Don't worry so much about understanding the details yet. Now, using the same callback function as above, lets demonstrate some more complex uses of this routine:

//2) Run example | Source for example.php
ajaxpack.getAjaxRequest("example.php", "name=George&age=27", processGetPost, "txt")
//3) Run example | Source for examplexml.php
ajaxpack.getAjaxRequest("examplexml.php", "product=Apple&cost=20", processGetPost, "txt")
//4) Run example
ajaxpack.getAjaxRequest("examplexml.php", "product=Apple&cost=20", processGetPost, "xml")
//5) Run example | Source for mylist.txt
ajaxpack.getAjaxRequest(ajaxpack.basedomain+"/mydir/mylist.txt", "", processGetPost, "txt")

As you can see, you can pass parameters to the receiving PHP script to process before returning some data accordingly for the callback function to alert. Notice the subtle difference between examples 3) and 4), which are identical in every respect expect the file type specified in the last parameter ("txt" or "xml'). The former causes the callback function to treat the returned data as regular text, which is why you see the actual source of the xml file alerted. The later causes a DOM XML representation of the XML file to be returned instead, which allows you to then easily parse it using standard DOM methods.

Example 5) is also note worthy, which shows using an absolute URL to reference the external file on your server. "ajaxpack.basedomain" is a variable you can use to return the current root domain of your server, taking into account whether "www" is present or not. For security reasons Ajax requires that the root domain of the page making the Ajax call and the receiving file be identical, down to the "www" portion or lack there of.

Performing asynchronous POST requests

You can also perform asynchronous POST requests via Ajax, which is arguably the more powerful of the two Ajax behaviours. Basically Ajax POST lets you send data from your page to a receiving server side script asynchronously via the POST method, without reloading the page. The data does NOT have to come from a form- it can be any content or value that you specify. Use Ajax Post instead of Ajax Get to send large amounts of information, or information from a FORM.

Ok, still using the original callback function above, processGetPost(), I'll show you a sample usage of using Ajax POST to send arbitrary information from the page to a PHP script asynchronously. I will just need a few new lines of new code to grab the data from the page I want to be posted and create a post string from it:

<h4 id="relatives">My uncle</h4>
<form id="myform">
Enter age: <input type="text" name="agefield" value="56" />
</form>

<script type="text/javascript">

function createpoststring(){
var namevalue=document.getElementById("relatives").innerHTML //get value to post from a DIV
var agevalue=document.getElementById("myform").agefield.value //get value to post from a form field
var poststr = "name=" + encodeURI(namevalue) + "&age=" + encodeURI(agevalue)
return poststr
}

//Step 3: Invoke the Ajax routine method to make the desired Ajax request.
var poststr=createpoststring() //Get contents to post and create query string first
ajaxpack.postAjaxRequest("postit.php", poststr, processGetPost, "txt")

</script>

Demo:

My uncle

Enter age: (try entering a different number)


Run example | Source for postit.php

In this example, I've sending information from the page to a PHP using the POST method. Notice how the information sent came from two different sources- a DIV tag and a form field. Try entering a different number into the "age" field, and see how the information sent and sent back changes accordingly.

More information

"So what's the point of alerting the contents of external files?" you ask. Well, this is just for illustration purposes. The key is to create your own the server side script (ie: example.php) and callback function (ie: processGetPost()) to perform exactly what you wish to accomplish asynchronously.

When performing Ajax requests on a server side script, you need to pay attention to security just as you would with a regular GET or POST request. This means checking the information sent to the server side script to ensure it's valid (ie: alphanumeric chars only), for example. With Ajax GET requests, this is especially important, since the user can easily modify the info sent, by modifying the name/value pairs in the URL string.