YOUR FEEDBACK
SCO - Linux' Worst Nightmare Is Back
cantstoplaughing wrote: Hi, I thought you got dropped by sys-con? What ha...
AJAXWorld RIA Conference
$300 Savings Expire July 18
Register Today and SAVE!

SYS-CON.TV

2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
TOP THREE LINKS YOU MUST CLICK ON


Tips & Tricks: AJAX – Not Just Limited to XMLHttpRequest
"There are many alternative ways of dynamically changing the current page, without refreshing it"

Digg This!

Page 2 of 2   « previous page

 

 

 

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

« previous page

About 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.

Shaurabh Bharti wrote: Thanks a lot to all of you to read my article with such large number.
read & respond »
Shaurabh Bharti wrote: 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.
read & respond »
AJAX head rush wrote: 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?
read & respond »
Web 2.0 Nonsense wrote: 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.
read & respond »
LATEST AJAXWORLD STORIES
Appcelerator Building Out the RIA Open Source Community
'We're dedicated to building the largest open-source community dedicated to RIAs, breaking down the barriers between traditional preferred languages, programming models and solutions,' says the co-founder & CEO of Appcelerator, Jeff Haynie, in this Exclusive Q&A with Jeremy Geela
AJAX World - Which RIA Tools Give Us the Best Bang for Your Buck?
In the world of Rich Internet Applications, there is no shortage of technology choices to compose a user interface. But what tools will give us the best bang for our buck? Here is a look at some heavy hitters and newcomers in the RIA market, including: HTML & AJAX, Rails and Grai
Saving Your Investment: Transforming J2EE applications into Web 2.0 using GWT
The pressure is on to keep pace with Web 2.0 entrants into the marketplace. Rewriting is expensive; adding AJAX widgets results in a complex, unmaintainable application. Both require you to hire scarce JavaScript developers. Google Web Toolkit -- the SDK that allows you to write
Gizmox Brings Microsoft Silverlight to Enterprises
Gizmox announced the release of a fully functional beta version of its Visual WebGui (VWG) with support for Microsoft Silverlight. For the first time, VWG enables Silverlight for enterprise applications by providing a RAD like Windows Forms development experience with drag & drop
How Linked Data and AJAR Changes Everything
The Web has evolved into a structured data space of loosely connected databases, enabling granular data access-by-reference to Web-accessible entities, courtesy of HTTP. This evolution and the emergence of AJAX-based RIA technologies lay the foundation for a new generation of lib
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE


ADVERTISE   |   MAGAZINE SUBSCRIPTIONS   |   FREE BREAKING-NEWSLETTERS!   |   SYS-CON.TV   |   BLOG-N-PLAY!   |   WEBCAST   |   EDUCATION   |   RESEARCH

.NET Developer's Journal - .NETDJ   |   ColdFusion Developer's Journal - CFDJ   |   Eclipse Developer's Journal - EDJ   |   Enterprise Open Source Magazine - EOS
Open Web Developer's Journal - OPEN WEB   |   iPhone Developer's Journal - iPHONE   |   Virtualization - Virtualization   |   Java Developer's Journal - JDJ   |   Linux.SYS-CON.com
PowerBuilder Developer's Journal - PBDJ   |   SEO / SEM Journal - SJ   |   SOAWorld Magazine - SOAWM   |   IT Solutions Guide - ITSG   |   Symbian Developer's Journal - SDJ
WebLogic Developer's Journal - WLDJ   |   WebSphere Journal - WJ   |   Wireless Business & Technology - WBT   |   XML-Journal - XMLJ   |   Internet Video - iTV
Flex Developer's Journal - Flex   |   AJAXWorld Magazine - AWM   |   Silverlight Developer's Journal - SLDJ   |   PHP.SYS-CON.com   |   Web 2.0 Journal - WEB2

SYS-CON MEDIA:   ABOUT US   |   CONTACT US   |   COMPANY NEWS   |   CAREERS   |   SITE MAP
SYS-CON EVENTS  |  AJAXWorld Conference & Expo  |  iPhone Developer Summit  |  OpenWeb Developer Summit  |  SOA World Conference & Expo  |  Virtualization Conference & Expo
INTERNATIONAL SITES:   India  |  U.K.  |  Canada  |  Germany  |  France  |  Australia  |  Italy  |  Spain  |  Netherlands  |  Brazil  |  Belgium
 Terms of Use & Our Privacy Statement     About Newsfeeds / Video Feeds
Copyright ©1994-2008 SYS-CON Publications, Inc. All Rights Reserved. All marks are trademarks of SYS-CON Media.
Reproduction in whole or in part in any form or medium without express written permission of SYS-CON Publications, Inc. is prohibited.