Sunday, April 15, 2012

Titanium HTTPClient, Sending a complex object

If you need to send a complex object on a request through the Titanium HTTPClient, an object that has more then a single level of data, for example:
var data_to_send={
   user:{name:'Gilad', l_name:'Manor'}
}
Passing this object, as is, to the HTTPClient will result in the server getting the sub object as a string, instead of an object.
To have this properly sent, you will need to wrap the data with JSON.stringify
i.e.

client.setRequestHeader('Content-Type', 
               'application/json; charset=utf-8');
client.send(JSON.stringify(data));




Tuesday, April 10, 2012

Titanium for Android and RoR

Lately, I've been playing around with the Titanium IDE for mobile development.
Its pretty nice once you get a hang of it.
My first application (code name Moris) I made to communicate as a mobile front end for the Gizmo server.

It came out rather simple since my API on the server side are aleady set to spit out JSON structures.



I've found that the simplest way is as following:
First I created a generic send function with a global client object:



var SERVER = 'https://YOUR-DOMAIN/api/';


var send = function (action, data, resFunc){
client.open("POST", SERVER+action);
  if (resFunc!=null) {
  client.setOnload(resFunc);
  };
  client.send(data);
}


var client = Ti.Network.createHTTPClient({
     onload : function(e) {
         alert('success '+this.responseText);
     },
     onerror : function(e) {
         alert('error');
     },
     timeout : 5000  /* in milliseconds */
 });


Then I add a specific function for each API I'd like to call on the server:


exports.login = function(user,pwd) {
send("login", {mail:user, password:pwd}, function(e) {
         //alert(this.responseData);
        Ti.App.fireEvent("gizmo_login_complete", JSON.parse(this.responseText));
     });
};


exports.userInfo = function(resultFunction) {
send("user_info", {data:null}, resultFunction);
};


In these two examples, I've Pass a function that would handle the particular case of returned data.
For the login, I fire a Titanium event that is caught on the app.js while for the user info I inject the function each I do the call.