Home » Guides Advanced Article

AdvancedAJAX 1.0

3.8/5.0 (4 votes total)
Rate:

Łukasz Lach
March 24, 2006


Łukasz Lach
Łukasz Lach has written 1 articles for JavaScriptSearch.
View all articles by Łukasz Lach...

001 Introduction

AdvancedAJAX is a JavaScript object allowing to use XMLHttpRequest object easier and speeding up development of AJAX based projects. It consists a bound of methods helping creating queries, error handling, usage with HTML forms as well as connection timeouts and reconnecting. AdvancedAJAX (so as AJAX itself) is fully supported by internet browsers listed below:

    * Internet Explorer - 5.0 and above (and other browsers using Microsoft's engine)
    * Mozilla - 1.0 and above (and other browsers based on Gecko engine)
    * Apple Safari - 1.2 and above
    * Opera - 7.60 and above

002 Usage


AdvancedAJAX contains methods allowing to create GET, POST and HEAD HTTP requests. It is also helpful when working with HTML forms.

The easier way is to use get(), post() and head() methods, depending on what type of HTTP request we would like to make. All listed methods take one argument – an object containing parameters describing HTTP request, error handling or reconnecting when connection times out. When given parameter is not known to AdvancedAJAX object it is added to HTTP query string.

The easiest usage of the object finishes at writing a couple of source code lines. The result of code presented below is an alert containing the document content downloaded from address given in the url parameter. It is saved in .responseText variable however, if we want to work with XML document, we can use .responseXML variable containing DOM object.

advAJAX.get({
    url: "http://www.example.com/page.html",
    onSuccess : function(obj) { alert(obj.responseText); }
});

The result of using post() method in example code above will change the type of request to POST only, the final result will remain unchanged. But what if request trigger an error, for example when requested file will not exist. Errors like that happen, but handling them with AdvancedAJAX is extremly easy. All you have to do is handle the onError event. Error code like 404 in case of file missing is saved under the .status variable and it's description (for example Not found) in .statusText (in Opera browser always null).

advAJAX.get({
    url: "http://www.example.com/page.html",
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); }
});

When requested file does not exist, handling onError like above will display an alert with Error: 404 text inside. AdvancedAJAX also allows to request pages that require username and password - these are also the names of parameters you have to add. When the pair of username and password are incorrect, the onError event will trigger with corresponding HTTP code saved under .status variable.

advAJAX.get({
    url: "http://www.example.com/page.html",
    username : "foo",
    password : "bar",
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); }
});

003 Parameters and headers


When using AdvancedAJAX it is extremly easy to set request arguments values and add extra headers. You can add argument using two methods - using parameters parameter or directly in URL. In case of giving parameter not known to AdvncedAJAX object it is also treated as an URL argument and added to final request string.

advAJAX.get({
    url: "http://www.example.com/page.html",
    parameters : {
      "var1" : "value1",
      "var2" : "value2"
    },
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); },
    "var3" : "value3"
});

Code above will request http://www.example.com/page.html?var1=value1&var2=value2&var3=value3 and that is because all parameters but var3 are known to object so it is moved to URL arguments list as well. If you use post() method here, all arguments will be sent in request content insted of header and that allows us to send huge ammount of data. The result of code below will be identical but here one argument is set directly in url parameter, second using queryString parameter and the last one in parameters object.

advAJAX.get({
    url: "http://www.example.com/page.html?var1=value1",
    queryString : "var2=value2",
    parameters : {
      "var3" : "value3"
    },
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); }
});

To send additional headers we can use headers parameter in the same way as we use described before parameters.

advAJAX.get({
    url: "http://www.example.com/page.html",
    headers : {
      "Custom-Header" : "value"
    }
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); }
});

004 Connection retry


AdvancedAJAX contains mechanizms responsible for connection retrying in case of error. Necessary thing here is to set the retry parameter that should contain the number of tries of retrying. It is also possible use retryDelay parameter to set the number of miliseconds between retries. Default value for that parameter is 1000, meaning 1 second. In case of error the onRetry event is triggered (which we can also modify) and before the delay between retries the onRetryDelay event triggers. One thing you have to remember is that connection retry is executed only when conection times out but not when, for example, 404 Not Found error happens. The maximum time of connection process before time out can be defined with timeout parameter that should contain number of miliseconds. After connection timeout the onTimeout event is triggeres, of course before onRetry.

advAJAX.get({
    url: "http://www.example.com/page.html",
    timeout : 3000,
    onTimeout : function() { alert("Connection timed out."); },
    retry: 2,
    retryDelay: 2000,
    onRetry : function() { alert("Retry connection..."); },
    onRetryDelay : function() { alert("Awaiting retry..."); },
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); }
});

Executing code above will result AdvancedAJAX to retry two times (so it will try to connect three times in total) in case of error. The delay between retries are set to two seconds. The maximum time of connection process is set to three seconds here. In case you want to check if connection timed out without using onTimeout event, there is an .aborted variable available which in this case will be set to true.


005 Temporary memory


Internet Explorer caches all results of AJAX requests. This means that even if requested page is changed Microsoft browser will use it's own cache and use localy saved data. Because of that AdvancedAJAX contains two parameters that can be modified. The unique parameter (implicitly true) defines if there should be an argument added to request arguments containing random value that will prevent saving it's result in cache. The name of described field can be set using uniqueParameter parameter (default set to "ajax_uniqid").

advAJAX.get({
    url: "http://www.example.com/page.html",
    uniqueParameter: "custom_unique_param",
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); }
});

006 Unlimited control


AdvancedAJAX contains a bound of additional events that gives you unlimited control on what happens before, during and after executed request. The first pair are onInitialization and onFinalization, both tiggered only once. onInitialization event is executed before creating XMLHttpRequest, onFinalization after all defined actions including connection retry or eventual error.

advAJAX.get({
    url: "http://www.example.com/page.html",
    onInitialization : function() {
        /* Hiding layer */
        someDiv.style.visibility = "hidden";
    },
    onSuccess : function(obj) {
        /* Set layer content to data received from server */
        someDiv.innerHTML = obj.responseText;
    },
    onError : function(obj) {
        /* In case of error we show an alert */
        alert("Error: " + obj.status);
    },
    onFinalization : function() {
        /* After all operations we show hidden layer */
        someDiv.style.visibility = "visible";
    }
});

The process of establishing connection and receiving data, in case of XMLHttpRequest, is divided into four parts. The order of executed events is following: onLoading, onLoaded, onInteractive and onComplete. Important thing here is that onComplete event is triggered even if AdvancedAJAX was unable to download requested URL. This means it is always executed before onSuccess and onError - be careful with that. The only exception is Opera browser on which onLoaded event is not triggered (due to incompatiable implementation of XMLHttpRequest).

advAJAX.get({
    url: "http://www.example.com/page.html",
    onLoading : function(obj) { /* Show 'loading' image */ },
    onComplete : function(obj) { /* Hide 'loading' image... */ },
    onSuccess : function(obj) { /* Show received data */ }
});

When critical error happens (for example when XMLHttpRequest object instance is being created or when requested URL uses other domain or unknown protocol) onFatalError event is triggered. If this happens, AdvancedAJAX finishes work executing onFinalization before.

Three columns listed below show example calls of events. First column is an example of successful creation of connection and receival of data, second when 404 Not Found error occurs and the last one shows two connection retries finally finished with failure.

onInitialization      onInitialization                 onInitialization
onLoading           onLoading                       onLoading
onLoaded            onLoaded                     onTimeout
onInteractive        onInteractive                  onRetryDelay
onComplete        onComplete                  onRetry
onSuccess          onError                             onLoading
onFinalization      onFinalization                  onTimeout
                                                                    onRetryDelay
                                                                    onRetry
                                                                    onLoading
                                                                    onTimeout
                                                                    onFinalization

007 HTML Forms


AdvancedAJAX contains two helpful methods when working with HTML forms. First one is .submit(), that takes value of all form fields and send it to URL saved under action parameter of form. This function takes two arguments - DOM object of form to be send (for example result of document.getElementById) and already explained list of AdvancedAJAX parameters os execution (which can be empty if we only want to send field's data).

advAJAX.submit(document.getElementById("the_form"), {
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); }
});

Second method is .assign(), that takes exactly the same pair of parameters as function explained before. Executing this function makes AdvancedAJAX to be executed after pressing form's submit button (or any other action causes form to send). This means AdvancedAJAX is being connected with the form and handles it's basic, send, action. What is important - if form already has onsubmit action set it's being saved and executed as well. In case of fatal error AdvancedAJAX stops execution and form is being send in traditional way.

advAJAX.assign(document.getElementById("the_form"), {});

To avoid multi-clicks on submit button AdvancedAJAX disables it as well as all form's fields for the time of execution. It's default action, however, it can be changed with disableForm parameter. Code below will connect AdvancedAJAX with form but during execution form's fields would not be disabled.

advAJAX.assign(document.getElementById("the_form"), {
   disableForm : false
});

008 Request grouping


When executing more than one request simultaneously we have no control on which one connects first ot finishes last... but not when using AdvancedAJAX. Handling onGroupEnter and onGroupLeave events and setting group parameter allowes us to do so. Practicly meaning - after grouping requests we will know when all of then finish to execute. Code below uses setDefaultParameters static method, described in next paragraph.

advAJAX.setDefaultParameters({
    group : "sample_group",
    onGroupLeave : function() { alert("Everything loaded..."); },
    onSuccess : function(obj) { alert(obj.responseText); },
    onError : function(obj) { alert("Error: " + obj.status); }
});
advAJAX.get({ url: "http://www.example.com/page1.html" });
advAJAX.get({ url: "http://www.example.com/page2.html" });
advAJAX.get({ url: "http://www.example.com/page3.html" });

009 Additions


In previous paragraph we used setDefaultParameters method. It's a static method that allows to set default parameters for .get(), .post(), .head(), .submit() and .assign() methods used afterwards. This lets us to avoid writing the same parameters several times including all events' actions. Thanks to setDefaultParameters method you can not only optimize your code but also make it much more readable.

Very simple but also much more useful property of AdvancedAJAX is tag parameter, that can contain string, numeric or any other value. It's modification does not change in the execution process - it just allows to save data of any type in the object. Code below shows how useful that parameter can be. It is used here to save an id of object into which received data from three different requests should be written.

advAJAX.setDefaultParameters({
    onSuccess : function(obj) {
    
        document.getElementById(obj.tag).innerHTML = obj.responseText;
    }
});
advAJAX.get({ tag: "layer1", url: "http://www.example.com/page1.html" });
advAJAX.get({ tag: "layer2", url: "http://www.example.com/page2.html" });
advAJAX.get({ tag: "layer3", url: "http://www.example.com/page3.html" });

____

This article was written by Łukasz Lach. Examples of the code in action can be seen at the author's website



Add commentAdd comment (Comments: 0)  

Advertisement

Partners

Related Resources

Other Resources

arrow