Welcome!

Linux Authors: Michael Sheehan, Lavenya Dilip, Ian Thain, Bruce Armstrong, Ellen Rubin

Related Topics: AJAX & REA

AJAX & REA: Article

Tips & Tricks: AJAX – Not Just Limited to XMLHttpRequest

"There are many alternative ways of dynamically changing the current page, without refreshing it"

 

 

 

Table 1. Common methods supported by XMLHttpRequest

Method

Description

open(method,URL,opt(asych.flag,username,password))

Opens server script using url. GET or POST could be one of method. Other elements are opt.

setRequestHeader(label, value)

Sets header of request

sent(data)

This is the content sent to server script.

getResponseHeader(label)

Returns single header value for label

getAllResponseHeaders()

Returns string containing all headers.

abort()

Aborts current request.

 

 

 

As by now, you have read the method names and their simple description. I shall explain their requirements.

xmlhttp.open() is used to open server script and establish connection. A typical example could be

 

 

 

xmlhttp.open(‘GET’,’server.php?queryString’,true);

 

 

 

Method can be POST or GET. Lets take GET method first. Variables are passed to server script through query string appended to the url. For example, name may be passed like following. escape() (javascript method) may be used to encode string into URL format. Third parameter is a boolean which specifies if

 

 

 

url = ‘server.php?name=sbharti’;

 

 

 

communication is asynchronous. If set, this does not wait for response from server, and continues to run the client script. This is an important point, for if server response does not reach to client due to network/server problems, client side does not hang and still continues to run. However, disadvantage is parameters are passed just as query string, which can be easily read on web. Hence, it brings security issues for sensitive information. Header of request shall also be properly set. In case of xml-based response, header should be set appropriate like below.

 

 

 

xmlhttp.setRequestHeader(‘Content-Type’,’text/xml’);

 

 

 

If header is not set, the response is assumed to be of text type only. Finally, Server script is invoked by sending null using operation send(). This is because data/content/parameters are already set in URL as query string. Hence server script extracts them from query string. Before calling send(), we would also

 

 

 

xmlhttp.send(“”);

 

 

 

need to set onreadystatechange (discussed below) which defines event-handler for request. This is actually a callback function which is called every time state of XMLHttpRequest changes and hence, keeps track of state and status of XMLHttpRequest object.

 

 

 

xmlhttp.onreadystatechange = responseHandler;

 

 

 

Second method type, ie POST is also used primarily for synchronous communication. A typical example for open() could be following. Note that parameters are not sent through query string. Instead, they are

 

 

 

            xmlhttp.open('POST',"server.php",false);

 

 

 

constructed in form of query string, and sent using send(). Header is set as below.

 

 

 

xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

 

 

 

Query string is formed, and finally send() is called to invoke server script.

 

 

 

queryString = “name=sbharti&email=shaurabh_bharti@infosys.com”;

 xmlhttp.send(queryString);

 

 

 

Note some direct differences in approach using GET and POST method. POST method is used primarily for synchronous communication. Parameters/content/data from client is sent in queryString format using send(queryString) operation. Note that while using POST method, we don’t really need to set onreadystatechange property of XMLHttpRequest here. This is because subsequent code is executed only when communication is complete.

An important limitation of XMLHttpRequest is it allows only local (to client script) server scripts to open. This is because it has sandbox security model.

 

 

 

Now that we are done with client requests, lets look at how client handles server responses. Before that, lets look at the common properties that XMLHttpRequest supports :-

 

 

 

Table 2. XMLHttpRequest properties

Property

Description

responseText

Data received in string format

responseXML

DOM object of data received provided in xml format

readyState

Various states supported are

0 = not initialized

1 = loading

2 = loaded

3 = partial response

4 = complete. Ready to access responseText

onreadystatechange

Event handler

status

Numeric code ret from server, ‘200’ means OK and 404 means NOT FOUND

statusText

Text with status code

 

 

 

Note that all properties are read-only except onreadystatechange. Clearly, any response (be it text of xml) should be accessed only after readyState has become ‘4’, i.e. when communication is complete. However, success or failure of communication can only be checked using status/statusText property. status with value ‘200’ or statusText with value ‘OK’ indicates successful communication, Now that communication has been successful, we may jump into processing response from server.

Event handler specified in property onreadystatechange  is called each time state of XMLHttpObject changes. It checks the state and status of XMLHttpRequest object, and takes action. Assuming everything went fine, response is extracted and processed else error messages are returned. Response from server in terms of content is stored in either responseText or responseXML. It depends on how the header for ‘Content-Type’ was set. Though responseText is string version of response, it shall be used in case of very simple communication. Property responseXML should be used in case of complicated communication. This returns a DOM compatible object, where almost all operations on node can be invoked. Hence, responseElem node is parsed just like a Document Object (W3C standard) to extract data.

 

 

 

var responseElem = xmlhttp.responseXML.documentElement;

or

var responseStr = xmlhttp.responseText;

 

 

 

This completes the communication cycle of XMLHttpRequest. Rest depends upon client to process the response.

ResponseTime from server could be an issue in certain cases and hence should be handled properly. This can be achieved by setting a global-timestamp for send() method. If send() method takes longer time than expected, abort() method may be called to stop communication.

 

 

 

 

 

 

 

 

 

 

 

 

5. Implementation Code

Server script : “returnID.php”

<?php

$id = $_POST["id"];

//create response for client

      print ‘The id received by server is : ‘.$id;

?>

 

 

 

Client Script: “newHtml.html”

 

 

 

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

<title>New Page </title>

<script language="JavaScript" type="text/JavaScript">

<!--

var xmlhttp = false;

function displayID(id){

    // for mozilla and safari

    if(window.XMLHttpRequest) {

      try {

       xmlhttp = new XMLHttpRequest();

        } catch(e) {

      xmlhttp = false;

        }

 

 

 

    // for IE windows

    } else if(window.ActiveXObject) {

            try {

            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

            } catch(e) {

            try {

               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

            } catch(e) {

              xmlhttp = false;

         }

      }

     

//    alert(xmlhttp);

      //synchronous comm.

   xmlhttp.open('POST',"returnID.php",false);

   xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');   

   xmlhttp.send("id="+id);

   if(xmlhttp.readyState==4){

            alert("Text from Server : "+xmlhttp.responseText);

        }

      }

 }

//-->

</script></head>

<body><form>

<input type="text" name="smtext" size="20"/>

<input type="button" value="Submit" onclick="displayID(this.form.smtext.value);" />

</form>

</body>

</html>

 

 

 

Implementation assumes proper configuration of php scripts on apache server 2.0.55, and JavaScript enabled in browser. Open ‘newHtml.html’ page on apache, enter some text in text box and click on Submit button. You shall see an alert displaying a message returned from server script. This example shows synchronous communication and uses POST method. I chose this example primarily because asynchronous communication using GET method is much  common implementation and hence documentation and examples are  readily available.

 

 

 

6. Alternatives to AJAX

AJAX is not just limited to XMLHttpRequest. There are many alternative ways to dynamically change current page, without refreshing it. In particular, the client-server interaction which XMLHttpRequest object offers, can be achieved by dynamic inclusion of JavaScript codes, which interact with backend server/code. Pre-built JavaScript codes may be added to current page using following code depending upon requirements.

 

 

 

function addNewFunction(url) {
  var newScript = document.createElement("script");
  newScript.src = url;
  document.body.appendChild(newScript);
}

 

 

 

However, only these steps does not really establish client-server interaction. This can be done by passing a callback function to new JavaScript code, which provides response through function parameters. Callback function is called when new JavaScript code is done with processing with input parameters (assuming the new js code knows callback function name). It passes its output as function parameter of callback to the client. Even more flexibility can be achieved by decoupling callback function. This can be achieved by passing the callback function name too as another parameter to new JavaScript code.

In all, basic aim of this method is 1) to modify a JavaScript code dynamically through server programming and using php (and others) 2) add the new is code to system through DOM functions and 3) call the new function. The steps are shown below :–

 

 

 

function addNewFunction(url, params) {
//params contain other query attributes + callback fn name

//append url with query attributes

url = url + params.

 

 

 

//add new is code

//when appenChild action on html DOM is taken, JavaScript code is dynamically created and put inside //page depending upon parameters passed to it.

var newScript = document.createElement("script");
  newScript.src = url;
  document.body.appendChild(newScript);
}

 

 

 

//some server code to produce new is like php

<?php

      //takes some action depending upon query string

//calls callback function finally, and passes response to it.

 print “$_GET[‘callback’]”(response)

?>

 

 

 

//some callback function inside

Function newCallback (response){

//takes action after parsing response

………………………..

………………………..

}

 

 

 

Even though this procedure looks more complicated than using XMLHttpRequest, it has potential to execute client-server interactions successfully. Also, it lags behind in terms of error handling, as there is no way to get a response back if callback function is not run, or code fails to execute etc. It does not support POST as well, where u may send more data and that too not through query string (as we saw for XMLHttpRequest).

 

 

 

7. References

         i.      http://developer.apple.com/internet/webcontent/xmlhttpreq.html

       ii.      http://en.wikipedia.org/wiki/AJAX

     iii.      http://www-128.ibm.com/developerworks/web/library/wa-ajaxintro1.html

      iv.      http://dotvoid.com/view.php?id=13

        v.      http://www.webreference.com/programming/ajax_tech

      vi.      http://adaptivepath.com/publications/essays/archives/000385.php

 

 

 

Table 1. Common methods supported by XMLHttpRequest

More Stories By Shaurabh Bharti

Shaurabh Bharti is a Junior Research Associate at Software Engineering and Technology Labs, Infosys Technologies Ltd. He works with Web Services Center of Excellence (WSCoE) team. A Computer Science graduate from IIT Kharagpur, he has been working with the team for almost an year. His current research interests include Semantic Web, Web Service, Contextual Collaboration etc. He has actively participated and conducted training sessions and workshops for Service Oriented Architecture and Web Services. He has also published papers in leading Journals and Conferences for Web Services including ICWS and IJWSP. He was one of the invited speakers at SOA and Web Services Seminar conducted by Vibrant Tech., Bangalore. He can be contacted at Shaurabh_Bharti@infosys.com.

Comments (4) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Shaurabh Bharti 04/29/06 03:59:05 AM EDT

Thanks a lot to all of you to read my article with such large number.

Shaurabh Bharti 04/24/06 04:43:52 PM EDT

Thanks for your comments!
However, I really dont think that because certain brwosers dont support javascript is a hindrance to web development. More than 90-95% hits on network happen with a javascript-enabled browser. Hence, improving UI functionality using them is quite worth to services offered via web.

AJAX head rush 04/22/06 08:19:39 AM EDT

With Head Rush Ajax, in no time you'll be writing JavaScript code that fires off asynchronous requests to web servers...and having fun doing it.

By the time you've taken your dynamic HTML, XML, JSON, and DOM skills up a few notches, you'll have solved tons of puzzles, figured out how well snowboards sell in Vail, and even watched a boxing match.

Sound interesting? Then what are you waiting for?

Web 2.0 Nonsense 04/22/06 07:31:50 AM EDT

I cant help but think the Web 2.0 obsession is getting out of hand. Its "poster child" is AJAX and, while this is useful, there are massive limitations to its implementation.

Add to this the potential learning curves involved and round off with the browser problems (what happens if the client doesn't have a JS enabled browser?) - all of a sudden it seems that this is actually a niche technology.

If you are designing a cutting edge site, geared to impress other web designers with your jedi-like editing powers then go for it. Web 2.0 your site to death.

If however, you are designing a site for the general public then steer clear.