Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Performing GET and POST requests using Ajax

Last updated: Sept 19th, 2009

Ajax, the catchy buzz word that ushered in the Web 2.0 era, basically describes two things once you strip away all the fluff: performing "GET" and "POST" requests asynchronously. Instead of using a FORM and requiring the user to explicitly submit it to transmit information back to the server, Ajax lets you perform such requests seamlessly at any time, using data that don't necessarily come from form elements, then get the result back without refreshing the page. Ok, that's a mouthful, but again, it all boils down to just two things- performing "GET" and "POST" requests and doing so asynchronously.

A typical GET request

A "GET" request refers to sending information to the server using parameters tacked on to the current page's URL This can be done by directly adding additional info to the page's URL:

http://www.javascriptkit.com/basicform.php?name=George&age=30

or using a FORM with its method set to "GET":

<form method="get" action="basicform.php">
Your name: <input type="text" id="name" name="name" size="25" /> <br />
Your age: <input type="text" id="age" name="age" size="25" /> <br />
<input type="submit" value="submit" />
</form>

This describes the traditional setup of a "GET" request. Now for the Ajax route instead.

A generic Ajax request object

Before we can make any sort of Ajax requests, we need to access the relevant object in the browser that facilitates asynchronous HTTP requests. window.XMLHttpRequest is your formal object, though it is NOT supported in IE6-, and in IE7, it's buggy. All other modern browsers support this object correctly. In IE browsers, there is an ActiveX alternative that can be used instead. Taking all of this into account, we'll roll a cross browser, generic Ajax object that will be the foundation for both of our GET and POST Ajax requests moving forward:

function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}

In IE, I'm testing for support for the various equivalents of the native "XMLHttpRequest" object in ActiveX. This includes IE7, which although supports "XMLHttpRequest" is buggy in its implementation. To create a new Ajax object instance, you always start with then:

var myajaxrequest=new ajaxRequest()

Where "myajaxrequest" is an arbitrary yet unique variable name.

Performing GET requests using Ajax

Time for our maiden Ajax "GET" request:

var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
 if (mygetrequest.readyState==4){
  if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
   document.getElementById("result").innerHTML=mygetrequest.responseText
  }
  else{
   alert("An error has occured making the request")
  }
 }
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
mygetrequest.send(null)

An Ajax GET request has the following pattern (the order is important):

  • An "onreadystatechange" event handler that's set to a function reference that will fire during each stage of the Ajax request. Use the Ajax object's "readyState" and "status" properties to determine when the request is complete before handling the returned data.
  • Call "ajaxobject.open()" with 3 parameters defined- the first one should always be "GET", the second one the full URL of the request (including any parameters), and finally, a 3rd parameter set to true. Notice the use of encodeURIComponent() to encode any special characters within parameter values.
  • Finally, call ajaxobject.send() with null entered as the single parameter.

Note that we're expecting the returned result in this example to be plain text/html. If the returned result is XML data instead, the method overrideMimeType('text/xml') should be called (more on this on the page "Retrieving an XML document using Ajax").

Here is the form at the beginning of this tutorial, but tweaked so it's submitted via Ajax GET instead:

Your name:
Your age:  

Result:

The form in this case simply becomes a way for the user to enter data, and doesn't do anything else. If the data is static, it very well may come from within a DIV or SPAN instead. It doesn't matter to Ajax, as the data is simply dynamically extracted using JavaScript, and can come from any source. Here's how the form in the above demo looks like:

<form method="get" action="">
Your name: <input type="text" id="name" name="name" size="25" /> <br />
Your age: <input type="text" id="age" name="age" size="25" /> <br />
<input type="button" value="submit" onClick="ajaxget()" />
</form>

<div id="result"> </div>

Where "ajaxget()" is simply the same Ajax GET request code posted above, but wrapped inside a function so it's called via "onClick" in this case. And here's the humble "myform.php" script btw:

<?
$name=htmlspecialchars($_GET['name']);
$name=stripslashes($name);
$age=(int)$_GET['age'];
echo "<span style='color:red'>Welcome <b>$name</b> to JavaScript Kit. So you're <b>$age</b> years old eh?</span>";
?>

"readyState", "status", and "statusText" properties

During an Ajax request, a few properties on the returned object inform you of the status of the request. The "readyState" keeps track of the current stage of the request by returning an integer:

  • 0: uninitialized
  • 1: loading
  • 2: loaded
  • 3: interactive
  • 4: complete

Typically you simply test for a value of 4 to know when the request is complete.

"status" returns the status code of the request, for example, "404" for a failed request, "200" for a successful one etc.  If you're running the Ajax request offline locally on your PC, a value of 0 is returned in some browsers regardless of the actual request status.

"statusText" returns a string describing the status of the request, such as "Not Found".

 Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.