Last Updated: March 10, 2022
·
629
· horiajurcut

XMLHttpRequest - A Different Approach

Let's declare our namespace:

var base = base || {};
    base.utils = base.utils || {};

Let's define what a Request object means:

base.utils.Request = function(options) {
    var self = this,
    response = null;

Using the options argument, we can map some initial properties:

this.method = options.method || 'GET';
this.URI    = options.url;
this.type   = options.type;
this.async  = !(options.async === false);

this.data   = null;

if (options.data != undefined && typeof options.data === 'object') {
    this.data = options.data;
}

Let's create an instance of XMLHttpRequest:

this.xhr = new XMLHttpRequest();

if (this.type != undefined) {
    this.xhr.responseType = this.type;
}

Here comes the tricky part. Instead of writing a series of conditionals (if statements), we can map callback functions to each HTTP Status Code:

this.callbacks = {};

this.callbacks[404] = options.notFound || null;
this.callbacks[200] = options.success || null;

Now, all we have to do is fire the correct callback function:

this.xhr.onreadystatechange = function(event) {
    if (this.readyState == 4) {
        response = this.response || null;

        self.callbacks[this.status] instanceof Function && self.callbacks[this.status].apply(self, [response]);
    }
}

It might be a good idea to have another callback function in case a network error occurs:

    this.xhr.onerror = function() {
        options.failure instanceof Function && options.failure.apply(this);
    }
};

3 Responses
Add your response

Btw. XMLHttpRequest has the wrong name... it hasn't been solely about XML for a long time.

over 1 year ago ·

@markushausammann It falls under the same category as HTTP_REFERER in PHP. Even if it's misspelled or improper, you're stuck using it :)

over 1 year ago ·