Skip to content

Instantly share code, notes, and snippets.

@stongo
Last active December 15, 2015 09:19
Show Gist options
  • Save stongo/5237800 to your computer and use it in GitHub Desktop.
Save stongo/5237800 to your computer and use it in GitHub Desktop.
sample titanium xhr constructor object
function Httpclient(url, method, entity, data) {
var url = url
, method = method || 'GET'
, entity = entity || 'entity'
, data = data || null;
this.contentType = "application/json; charset=utf-8";
this.onload = function(e) {
Ti.API.log('Httpclient log for ' + entity + '. Response: ' + this.responseText + 'Status: ' + this.status);
}
this.onerror = function(e) {
Ti.API.log('Httpclient error log for ' + entity + '. Response: ' + e.error + 'object: ' + JSON.stringify(e));
alert('There was a problem performing your request.');
}
this.execute = function() {
var client = Ti.Network.createHTTPClient({
timeout: 8000,
onload: this.onload,
onerror: this.onerror
});
client.open(method, url);
client.setRequestHeader('Content-Type', this.contentType);
client.send(data);
}
}
module.exports = Httpclient;
var SITE_PATH = 'http://mypath.com/'
var REST_PATH = SITE_PATH + 'services/rest/';
...
// use the client like this anywhere in your app
Ti.include('config.js');
var Client = require('Client');
var url = REST_PATH + 'resource/path/of/service';
var entity = 'user';
var data = JSON.stringify(myData);
var Httpclient = new Client(url, 'POST', entity, data);
// Optionally override default onload event listener
Httpclient.onload(e) {
alert('it worked');
}
Httpclient.execute();
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment