Simple Async HTTP Module for Appcelerator


Hello techies,

I have been using Appcelerator recently. It is a pretty cool tool, it allows you to create cross platform mobile applications for iOS and Android, writing JavaScript.

Appcelerator’s Titanium Framework uses the CommonJS API so you can reference javascript files as “modules”, it is very reminiscent of node.js which also implements CommonJS.

Below is a simple async module I wrote, inspired by codeboxed’s gist, to make requests to a web server. Stick it in a file named SimpleHttpAsync.js

  //////////////////////////////////////////////
 //                Simple Http Async         //
//////////////////////////////////////////////

exports.call = function (options) {
    //create the titanium HTTPClient
    var httpClient = Titanium.Network.createHTTPClient();

    //set the httpclient's properties with the provided options
    httpClient.setTimeout(options.timeout);
    httpClient.onerror = options.error;
       
    //if and when response comes back
    //the success function is called
    httpClient.onload = function(){
        options.success({
            data: httpClient.responseData, 
            text: httpClient.responseText
        });
    };
        
    //open the connection
    httpClient.open(options.type, options.url, true);

    //send the request
    httpClient.send();
};

The following is example code of importing and using the module

//import the module
var simpleHttpAsync = require('simpleHttpAsync');

//call the function
//handle errors and successful request
simpleHttpAsync.call({
    type : "POST",
    url : "http://www.someurl.com?somekey=somevalue",
    error : function (error) {
        //do something to handle error
    },
    success : function (response) {
        //do something with the response data from the server
    },
    timeout : 10000
});

It’s nothing special, but the documentation for Appcelerator is pretty sparse and I thought it might be useful for those new to the Appcelerator Titanium Framework.

As always enjoy and let me know if you have any comments/suggestions/questions. Thanks!

Simple XML to JSON with PHP