Tuesday, March 23, 2010

Ajax Simplified Steps

Ajax Simplified Steps

This is my 1st post in my technical blog , i will show here different technical topics, i will try to simplify the steps needed to implement different technologies and post some tutorials to show the basic concepts behind them.

In this post i am showing how to use the Ajax technology in few simple steps describing the technology basics, the 2nd post will show a real project that uses Ajax.

Let's begin with the steps that we need to implement Ajax in our web projects:

1.Create Request Object:

request = new XMLHttpRequest();

-This is the object that we will use to open the connection.

2.Call Open method:

request.open([HTTP method], [URI], Async, [Basic auth username], [Basic auth password]);

-Here we open the connection using the required http method (Post, Put, Get, ...),URI is the requested URI , aynch = true/false for asynchronous or not.

3.Setup Handler method:

request.onReadyStateChange = [Name of handler function];

-The handler method is the method that will receive the response of our request, so it can process it.

4.Send header information:(if needed)

request.setRequestHeader([Header name], [Header value]);

-If we need to send specific header attribute , like needed response type ,..etc., we use this method to set this header parameter.

5.Send the request:

request.send([Entity-body]); //null if not PUT or POST

-This method submit the request.

6.Handler method called with status:

- The handler method usually check if the response is return or not and the response status code for example readyState=4 means the response is ready now , e.g.

If(request.readyState==4 [&& request.status == 200]) {
//do UI changes

The possible Ready Status values are:
0 = Unsent
1 = Opened
2 = Header Received
3 = Loading
4 = Done

So Done here doesn't mean success , so you need to check on the response status is 200 which means OK.

* 2 Response Types available:

* responseXML: DOM object representing the response document—assuming it was served as XML and the browser can parse it
* responseText: response document as a raw string—useful when it’s JSON or some other non-XML format

7.Get Response Header Info:
(if needed)


-In case you expected certain header attributes in the response, you can use this method to retrieve it.

**Cross Platform Issue

To enable it to work in all browsers you need to get the request object correctly,so replace this method :

request = new XMLHttpRequest();

request = createXMLHttpRequest();

function createXMLHttpRequest() {
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("XMLHttpRequest not supported");

Parsing the Response:

To Parse the response you can have it as XML or non-XML (mostly JSON):

Parsing XML Response

function myHandler() {
if (request.readyState == 4) {
var root = request.responseXML;
var addrsElem = root.getElementsByTagName('addresses')[0];
var firstAddr = addrsElem.getElementsByTagName('address')[0];
var addrText = fistAddr.firstChild;
var addrValue = addrText.nodeValue;

Parsing JSON Response

function myHandler() {
if (request.readyState == 4) {
var card = eval('(' + request.responseText + ')');
addrField.value = card.addresses[0].value;

JSON Security Vulnerability:

a) If the data and the entire JavaScript environment is not within the control of a single trusted source.
b) If the data is itself not trusted, for example, it may be subject to malicious JavaScript code injection attacks; unless some additional means is used to validate the data first.

How to avoid this ?

By using 1 of the 3 options listed here:

1) The RFC that defines JSON (RFC 4627) suggests using the following code to validate JSON before using “eval”:

var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( text.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + text + ')');

2) A new function, parseJSON(), has been proposed
-Safer alternative to eval, as it is specifically intended to process JSON data and not JavaScript.

3)Native JSON encoding/decoding
-Faster compared to the JavaScript libraries
-Supported in IE8, FF3.5, Chrome,….etc.

No comments:

Post a Comment