• AJAX 07.05.2009 1 Comment

    Ajax stands for Asynchronous JavaScript and XML and is a set of techniques for creating highly interactive web sites and web applications. The desired result is to update the website pages, using data fetched from the Internet, without refreshing the web page in the users’ browser.

    The communication between the server and the web browser is done using XMLHttpRequest objects manipulated through a JavaScript function. The goal is to create a JavaScript function which, based on users action, will change the data displayed on users’ browser following some well defined rules.

    Creating the XMLHttpRequest Object

    This object is built in the browser and, depending on what browser you are running the code, it is accessed in different way. Netscape Navigator (version 7.0 and later), Apple Safari (version 1.2 and later), and Firefox let you create XMLHttpRequest objects with code like this:

    XMLHttpRequestObject = new XMLHttpRequest();

    In case that you are dealing with Internet Explorer the object can be created using code like this:

    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);

    The object is accessed in those browsers through the browser window object, and checking it’s presence means that you are dealing with certain web browsers.

    For Netscape, Safari and Firefox the code will be as follows:

    if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
    }

    For Internet Explorer we’ll have:

    if (window.ActiveXObject) {
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
    }

    Although the XMLHttpRequest object supported in different browsers differs we can use the same basic properties and methods of this object.
    So, the code used to create XMLHttpRequest object for different web browsers will be:

    var XMLHttpRequestObject = false;
    if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
    }

    Opening the XMLHttpRequest Object

    It’s time to open the XMLHttpRequest object. Here’s how you use the XMLHttpRequest object’s open method in general (items in square brackets are optional, and items in italics are placeholders that you fill in yourself):

    open(“method”, “URL”[, asyncFlag[, "userName"[, "password"]]])

    Where method is the HTTP method used to open the connection, such as GET, POST, PUT, HEAD, or PROPFIND, URL is the requested URL, asyncFlag is a boolean value which indicates if the call is asynchronous (default value true), userName is the user name of your account and the password is the password of your account.

    The method used to open the connection will be for this case the GET method. After the connection is open, we can start to open the XMLHttpRequest object and to configure it in preparation for connecting to the server and downloading data.

    This piece of JavaScript code will prepare the object:

    XMLHttpRequestObject.open(“GET”, dataSource);

    Note that using the open method like this configures the XMLHttpRequest object and it does not connect, or open any connection to the server.

    The onreadystatechange property contains the name of the event handler that should be called when the value of the readyState property changes (read/write). Using this property we can call an anonymous function that will open the connection to the server and to download the necessary data. Inside the anonymous function, we need to check on the data that’s been downloaded: is the download complete and are we ready to use that data? We can determine that with two properties of the XMLHttpRequest object: readyState and status.

    The value of 4 for the readyState property means that the download is complete and the value of 200 for the status property means that is completed OK. Checking these values with an if statement which returns the true value means that we can go further with our request.

    The JavaScript code will be as follows:

    XMLHttpRequestObject.onreadystatechange = function(){
    if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
    {//here we’ll place the necessary code to fetch the data}
    }

    To recover the downloaded text we can use the XMLHttpRequest object’s responseText property. That property is where the XMLHttpRequest object stores downloaded plain text. If we use XML data the object property will be responseXML (we’ll use it a little bit later) which is common for all major browsers.

    The JavaScript code will be:

    documentGetElementById(divID).innerHTML = XMLHttpRequestObject.responseText;

    where the element with the divID id will be the placeholder for our requested data.

    Connecting to the server

    In this example, we’re using the GET method, so we call the XMLHttpRequest object’s send method, passing it a value of null, which is JavaScript’s placeholder for a value of nothing.

    The JavaScript code will be:

    XMLHttpRequestObject.send(null);

    At this point we have created the XMLHttpRequest object, we opened it and we have created the connection to the server. From now we can make useful XML to store data and to have the source for our Ajax requests.

    Using Ajax with XML

    In the Firefox/Mozilla brand of browsers, we have to specify that we’re going to be downloading XML data, not plain text. To do that, we have to set the MIME type of the download to text/xml. We can achieve this using this line of code:

    XMLHttpRequestObject.overrideMimeType(“text/xml”);

    Another difference will be that we will use the XMLHttpRequest object’s responseXML property, which holds a JavaScript XML document object:

    var xmlDocument = XMLHttpRequestObject.responseXML;

    Let’s say that we want to download data regarding streets name from a certain city area (Bucharest in my case). For this we have to create a variable streetsName which will hold the data parsed from the XML file ruled by the Tag Name read-only property:

    streetsName = xmlDocument.getElementsByTagName(“streetName”);

    After this we need to create the format for the placeholder of the data. In this case I will create a list of elements <span> displayed as block. Maybe it will be better to generate elements of an unordered list, but the problem is that, using the following sequence of JavaScript code, the HTML output will be a type of <ul></ul><li>...</li>, which means that we have an empty ul element and some orphans li elements, and this could lead to problems on CSS formatting.

    The necessary code will be:

    var xmlDocument = XMLHttpRequestObject.responseXML;
    streetsName = xmlDocument.getElementsByTagName("streetName");
    obj.innerHTML = "Here are the fetched streets name:";
    for (loopindex = 0; loopIndex < streetsName.length; loopIndex++)
    {
    obj.innerHTML += "<span>" + streetsName[loopIndex].firstChild.data + "</span>";
    }

    where obj = document.getElementById(divID); which is the container of our data.

    The structure of the XML file will be simple:

    <?xml version="1.0" ?>
    <streetsName>
    <streetName>Calea Victoriei</streetName>
    <streetName>Regina Elisabeta</streetName>
    <streetName>Lascar Catargiu</streetName>
    <streetName>Iuliu Maniu</streetName>
    <streetName>Cotroceni</streetName>
    <streetName>Ion Ionescu de la Brad</streetName>
    <streetName>Calea Dorobantilor</streetName>
    </streetsName>

    From now the only thing we need to create is a form element which, based on user click action, will execute the function that will fetch the desired data from server.

    The entire code (HTML and JavaScript) can be downloaded from the following link, a simple example on how data is fetched form server using Ajax and XML.

    • Share/Bookmark

    Tags: , ,

Polls

New blog template! What do you think?

View Results

Loading ... Loading ...

 

May 2009
M T W T F S S
« Apr   Jul »
 123
45678910
11121314151617
18192021222324
25262728293031
ally-disappointed