| By Shaurabh Bharti | Article Rating: |
|
| April 22, 2006 12:30 PM EDT | Reads: |
22,515 |
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
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
Published April 22, 2006 Reads 22,515 More Stories By Shaurabh BhartiShaurabh 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. Most Recent Comments
|
Comments
Topics |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
































