Search code examples
javascripttitanium

Get data from webpage in Titanium


I've made a small piece of code in titanium to get data from a webpage. But when i run the application and press the button that will trigger the function it doesn't show the data.

Can someone explain to me what i am doeing wrong, and why i did it wrong?

This is my code:

// include needed files
Ti.include('responsive.js');
//Ti.include('http_connection.js');


//Create the screen

//The home screen
var homeWindow = Ti.UI.createWindow({
  exitOnClose: true,
  fullscreen: false,
  title: 'Advanced'
});

var homeView = Ti.UI.createView({
  backgroundColor: 'white'
});

var homeLabel = Ti.UI.createLabel({
    top: 20,
    left: 30,
    height: 30,
    text: 'Test text',
    color: 'black',
    font: {fontSize: 18}
});

var testButton1 = Ti.UI.createButton({
    title: 'test',
    backgroundColor: 'red',
    top: 55,
    left: per10,
    width:per60,
    height: 30,
    color: 'black',
    font: {fontSize: 14} 
});

var testButton2 = Ti.UI.createButton({
    title: 'test2',
    backgroundColor: 'blue',
    top: 95,
    left: per10,
    width:per60,
    height: 30,
    color: 'black',
    font: {fontSize: 14} 
});

testButton2.addEventListener('click',function(e){
    Ti.API.info("Button Clicked");
    http_con();
    Ti.API.info("Button Clicked 2");
    //alert('test');
});

function http_con() {
    Ti.API.info('hya');

    //Database connection
    var http_client = Ti.Network.createHTTPClient();
    http_client.open('POST', 'http://rdbomers-hp:89/ceres');

    //If variables has been send
    http_client.onload = function() {
        Ti.API.info('subjects: ' + this.responseText);
        callback(this.responseText);
    };

    //If there is an error
    http_client.onerror = function(e) {
        Ti.API.info('error: ' + JSON.stringify(e));
    };
};

//Creating the application
//Home screen
homeWindow.add(homeView);
homeView.add(homeLabel);
homeView.add(testButton1);
homeView.add(testButton2);
homeWindow.open();

I have put thi Ti.API.info('hya') in the function to check if it gets there, it shows the HYA, but i want it to show the content of the webpage.


Solution

  • You should define callbacks before calling .open - like this

    function http_con() {
        Ti.API.info('hya');
    
        //Database connection
        var http_client = Ti.Network.createHTTPClient();
    
        //If variables has been send
        http_client.onload = function() {
            Ti.API.info('subjects: ' + this.responseText);
            callback(this.responseText);
        };
    
        //If there is an error
        http_client.onerror = function(e) {
            Ti.API.info('error: ' + JSON.stringify(e));
        };
    
        http_client.open('POST', 'http://rdbomers-hp:89/ceres');
    
    };