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.
1 Answer
-
You need a
onerror()
callback to catch error if anyxhr.onload = function(){ Ti.API.info(this.responseText); ... } xhr.onerror = function(e){ Ti.API.info( JSON.stringify(e) ); }
Best,
Minh