HTTP Request //JavaScript Repository

Description

Class to make remote requests, which can be used on the popular "AJAX".
Created: 2006.08.18

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/http-request [rev. #1]

HTTPRequest = function(){};
with({$: HTTPRequest.prototype}){
    $.isSupported = function(){
        return !!this.getConnection();
    };
    $.events = ["start", "open", "send", "load", "end"];
    $.filter = encodeURIComponent;
    $.getConnection = function(){
        var i, o = [function(){return new ActiveXObject("Msxml2.XMLHTTP");},
        function(){return new ActiveXObject("Microsoft.XMLHTTP");},
        function(){return new XMLHttpRequest;}];
        for(i = o.length; i--;) try{return o[i]();} catch(e){}
        return null;
    };
    $.formatParams = function(params){
        var i, r = [];
        for(i in params) r[r.length] = i + "=" + (this.filter ? this.filter(params[i]) : params[i]);
        return r.join("&");
    };
    $.get = function(url, params, handler, waitResponse){
        return this.request("GET", url + (url.indexOf("?") + 1 ? "&" : "?") + this.formatParams(params), null, handler, null, waitResponse);
    };
    $.post = function(url, params, handler, waitResponse){
        return this.request("POST", url, params = this.formatParams(params), handler, {
            "Connection": "close",
            "Content-Length": params.length,
            "Method": "POST " + url + " HTTP/1.1",
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
        }, waitResponse);
    };
    $.request = function(method, url, params, handler, headers, waitResponse){
        var i, self = this, o = self.getConnection(), f = handler instanceof Function;
        try{
            o.open(method, url, !waitResponse);
            waitResponse || (o.onreadystatechange = function(){
                var s = $.events[o.readyState];
                handler && (f ? handler(o) : s in handler && handler[s].call(self, o));
            });
            if(headers){
                for(i in {USER_AGENT: 0, XUSER_AGENT: 0})
                    i in headers || (headers[i] = "XMLHttpRequest");
                for(i in headers)
                    o.setRequestHeader(i, headers[i]);
            }
            o.send(params);
            waitResponse && handler && (f ? handler(o) : handler["end"] && handler["end"].call(self, o));
            return true;
        }
        catch(e){
            return false;
        }
    };
}

Example (Example)

<fieldset>
    <legend>HTTPRequest example</legend>
    <input type="button" value="POST request with generic listener and params passage" onclick="genericHandler()" />
    <br /><input type="button" value="GET request with specific listener (binded on load and end)" onclick="specificHandler()" />

<script type="text/javascript">
//<![CDATA[

var r = new HTTPRequest;

function myHandler(o){
    alert("Current event = " + r.events[o.readyState] +
    '\nAvailable "responseText.length" = ' + o.responseText.length);
}
function genericHandler(){
    r.post(location.href, {param: "abcde", name: "Jonas", site: "http://jsfromhell.com"}, myHandler);
}
function specificHandler(){
    r.get(location.href, null, {load: myHandler, end: myHandler});
}
document.write(
    "<br />Supports XMLHTTPRequest = ".bold() + r.isSupported(),
    '<br />Encoded with the default filter ("encodeURIComponent") = '.bold() + r.formatParams({nameA: "aeiou", nameB: "????"})
);

r.filter = escape;
document.write('<br />Encoded with "escape" filter = '.bold() + r.formatParams({nameA: "aeiou", nameB: "????"}));

r.filter = null;
document.write("<br />Encoded with no filtering = ".bold() + r.formatParams({nameA: "aeiou", nameB: "????"}));

//]]>
</script>
</fieldset>

Help

Constructor

HTTPRequest(void)
Generates a new instance of HTTPRequest. On the requests the class will identify itself on the HTTP_USER_AGENT header as "XMLHTTPRequest"

Properties

HTTPRequest.filter: Function(data: String): String
function that will be called to filter the values of the parameters, by default it will be used the "encodeURIComponent" function

Methods

Observation: There are two ways of setting the callbacks, if you pass a simple function, it will be called for all the events of the XMLHTTPRequest, the other way is to set just the desired events on the callback, using the following sintax: {eventName: callback, eventName2: callback, ...}, where the allowed events are:

  • open = called after the request start
  • sent = called after the request data is sent
  • load = called multiple timples while the content is retrieved
  • end = called in the transference end

HTTPRequest.isSupported(void): Boolean
Returns true if the browser supports the creation of the XMLHTTPRequest object.
HTTPRequest.get(url: String, [params: Object = null], [handler: Function(xhr: XMLHTTPRequest): void = null], [waitResponse: Boolean = false]): Boolean
Makes a request through GET and returns true if the request is created succesfully.
url
request url
params
parameters hashmap, it will be serialized and added on the end of the url as query string
handler
callback that will be called on the XMLHTTPRequest events, receives as argument the own XMLHTTPRequest object
waitResponse
indicates if the request will be synchronized (true) or asynchronized (false)
HTTPRequest.post(url: String, [params: Object = null], [handler: Function(xhr: XMLHTTPRequest): void = null], [waitResponse: Boolean = false]): Boolean
Makes a request through POST and returns true if the request is created succesfully.
url
request url
params
parameters hashmap, it will be serialized and on sent within the POST
handler
callback that will be called on the XMLHTTPRequest events, receives as argument the own XMLHTTPRequest object
waitResponse
indicates if the request will be synchronized (true) or asynchronized (false)
HTTPRequest.request(method: String, url: String, [params: Object = null], [handler: Function(xhr: XMLHTTPRequest): void = null], [headers: Object = null] [waitResponse: Boolean = false]): Boolean
Makes a request and returns true if the request is created succesfully.
method
method that will be used to make the request
url
request url
params
parameters hashmap, it will be serialized and on sent within the POST
handler
callback that will be called on the XMLHTTPRequest events, receives as argument the own XMLHTTPRequest object
headers
hashmap containing additional headers
waitResponse
indicates if the request will be synchronized (true) or asynchronized (false)
HTTPRequest.getConnection(void): XMLHTTPRequest
Returns a new XMLHTTPRequest object or null on error.
HTTPRequest.formatParams(params: Object): String
Serializes the hashmap into the "query string" format.
params
object which the properties will be serialized

Rank (Votes: 50)

3.88