Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

JSON and HTTP to get MySQL... Not working?

Alright, so I need to connect to a MySQL database to get some information, but everything I am trying isn't working. Here is what I have on my App:

var win = Titanium.UI.currentWindow;

var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(){
    var json = JSON.parse(this.responseText);
    if (!json) { 
        Titanium.API.info('Error - Null return!'); 
        return;
    }
    var jsoncats = json.episodes;
    var pos;
    for( pos=0; pos < jsoncats.length; pos++){
        Ti.UI.info(jsoncats[pos].title, jsoncats[pos].episode);
    }
};
xhr.open('GET', 'URL-TO-PHP-FILE');
xhr.send();

And here is what is in the .PHP file that is grabbed by the App:

<?php
$mysqli = new mysqli("HOST","USERNAME","PASSWORD","DBNAME");
if (mysqli_connect_errno()) {
    printf("Cannot connect to MySQL Server. Contact webmasters. \n", mysqli_connect_error($mysqli));
    exit;
}
$mysqli->query("SET NAMES 'utf8'");
$json = array();
if($result = $mysqli->query("SELECT * FROM episodes")) {
    while ($row=$result->fetch_assoc()) {
        $json[]=array(
            'title'=>$row['title'],
                        'episodes'=>$row['episodes']
        );
    }
}
$result->close();

header("Content-Type: text/json");
echo json_encode(array('episodes' => $json)); 

$mysqli->close(); 
?>

What I'm ultimately trying to do: Pull the data, then display it in a custom TableView that I have self-designed.

— asked August 31st 2010 by Colton Arabsky
  • connect
  • mysql
2 Comments
  • Did you ever get this working? stuck in the same problem for days now…

    — commented February 17th 2012 by Mark Schellhas
  • Mark, have you tried using responseData instead of responseText?

    I'd recommend posting a new question with your problem.

    — commented February 17th 2012 by Allen Hartwig

1 Answer

  • You need a onerror() callback to catch error if any

    xhr.onload = function(){
        Ti.API.info(this.responseText);
        ...
    }
    
    xhr.onerror = function(e){
        Ti.API.info( JSON.stringify(e) );
    }
    

    Best,

    Minh

    — answered February 17th 2012 by Minh Nguyen
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.