Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Web Development

AJAX & Record Locking


A Reusable HttpRequest Type

Because JavaScript offers basic object-oriented encapsulation, it is possible to build a reusable HttpRequest JavaScript type that wraps a more desirable API around the HttpRequestObject's API. Listing Two is our version of this, and it has been borrowed almost entirely from code in Ajax in Action by Dave Crane et al. (which, incidentally, has a nice section on object-oriented JavaScript). The net.ContentLoader type in this code demonstrates the technique of using a JavaScript Object variable as a namespace to which to add a type definition. The trimString function, all the READYSTATE_ constants, and the ContentLoader constructor and full prototype are defined in the net namespace.

// HttpRequestObject in net namspace
var net = new Object();
net.trimString = function(inString) { return 
   inString.replace( /^\s+/g, "" ).replace( /\s+$/g, "" ); } 
      // belongs in another namespace
net.READYSTATE_UNITITIALIZED=0;
net.READYSTATE_LOADING=1;
net.READYSTATE_LOADED=2;
net.READYSTATE_INTERACTIVE=3;
net.READYSTATE_COMPLETE=4;
net.ContentLoader = function()
{
    this.req = null;
    this.doc = null;
    this.text = null;
    this.url = null;
    this.onload = onload;
    this.onerror = this.defaultError;
}
net.ContentLoader.prototype =
{
    load:function(url)
    {
        if(window.XMLHttpRequest) this.req = new XMLHttpRequest();
        else if(window.ActiveXObject) this.req = 
                   new ActiveXObject('Microsoft.XMLHTTP');
        if(this.req)
        {
            try
            {
               this.setUrl(url);
                var loader = this;
                this.req.onreadystatechange = function() {
                   loader.onReadyStateHandler.call(loader); }
                this.req.open('POST', url, true);
                this.req.send(null);
            }
            catch(err)
            {
                this.onerror.call(this);
            }
        }
    },
    onReadyStateHandler:function()
    {
        var ready = this.req.readyState;
        if(ready == net.READYSTATE_COMPLETE)
        {
            if(this.req.status == 200 || this.req.status == 0)
            {
                this.setText(this.req.responseText);
                this.setXml(this.req.responseXML);
                this.onload.call(this);
            }
            else this.onerror.call(this);
        }
    },
    defaultError:function()
    {
        alert("Error with AJAX communication"
            + "\nURL: " + this.url
            + "\nreadyState: " + this.req.readyState
            + "\nstatus: " + this.req.status
            + "\nheaders: " + this.req.getAllResponseHeaders());
    },
    setResponseHandler:function(handler) { this.onload = handler; },
    setErrorHandler:function(handler) { this.onerror = handler; },
    setUrl:function(url) { this.url = url; },
    getUrl:function() { return this.url; },
    setXml:function(doc) { this.doc = doc; },
    getXml:function() { return this.doc; },
    setText:function(text) { this.text = text; },
    getText:function() { return this.text; }
}
Listing Two

An instance of HttpRequest goes through the process of contacting the server, making the request, and receiving back the server's response. As it goes through these steps, it calls back to HttpRequestObject.onReadyStateChange, for which you can supply a function handler. Typically, your handler checks the value of HttpRequestObject.readyState to see if it indicates that the server's response is complete. Once the server's response finishes and the value of HttpRequestObject.status indicates that the server's response succeeded, the HttpRequest object calls onload, which is the key response-handling function supplied by developers. This is, for example, where we place the code that examines the server's status messages and hides or shows the Edit button.

The constructor of the net.ContentLoader type assigns default event handlers for onload and onerror. The default onerror handler (which pops up an alert when an AJAX call fails) is net.ContentLoader.defaultError, a function of the net.ContentLoader prototype. The error handler may be reassigned through net.ContentLoader.setErrorHandler. The default onload handler is defined as a global onload method, which is defined outside of the net.ContentLoader prototype and consequently must be supplied by users of the net.ContentLoader. It's a good idea to supply a specialized handler through the net.ContentLoader.setResponseHandler function; otherwise, all instances of the net.ContentLoader on the same page end up using the same response-handling function.

When the window.onload function runs in our application, it runs on a page that is either read-only or editable. window.onload creates a net.ContentLoader object for us:


var contentLoader = new net.ContentLoader();



Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.