Hi,
I have the following code to call one of my PHP files which retrieves data from a MySQL database and returns what I'm trying to do some JSON (records):
var params = "?deviceId=" + "123456"; // this would be + Ti.Platform.id var encodedURI = encodeURI("http://exposed.theappmediaco.com/API/GetOrders.php" + params); var xhr = Titanium.Network.createHTTPClient({ onload : function(){ Ti.API.info(this.responseText); var parsedData = JSON.parse(this.responseText); var amount = parsedData.data.length; Ti.API.debug(amount); var json = JSON.parse(this.responseText); Ti.API.info('end onload'); if (!json) { Titanium.API.info('Error - Null return!'); return; } var jsoncats = json.orders; Ti.API.info(jsoncats.length); var pos; for( pos=0; pos < jsoncats.length; pos++){ Ti.UI.info(jsoncats[pos].tshirtStyle, jsoncats[pos].tShirtSize, jsoncats[pos].dateOrdered); } }, onerror : function(e) { Ti.API.debug(e.error); }, timeout:10000 }); xhr.open("GET", encodedURI); xhr.send();and the PHP:
<?php $deviceId = $_GET['deviceId']; // get the device id - this is the PK on DB echo $deviceId; $con = mysql_connect('82.218.214.98','usrname','password'); if(!$con) { die('Could not connect: ' . mysql_error()); } echo "DB Connection made"; // Select the relevant DB mysql_select_db("database",$con); $result = mysql_query("SELECT * FROM orders where customerId=$deviceId"); $json = array(); while($row = mysql_fetch_array($result)) { $json[] = array ( 'tshirtStyle'=>$row['tshirtStyle'], 'tShirtSize'=>$row['tShirtSize'], 'dateOrdered'=>$row['dateOrdered'] ); // echo $row['tshirtStyle'] . " " . $row['tShirtSize'] . " " . $row['dateOrdered']; // echo "|"; // | is the sentinel to check for, i.e end of record } header("Content-Type: text/json"); echo json_encode(array('orders' => $json)); mysql_close($con); ?>The line var parsedData = JSON.parse(this.responseText); seems to do nothing and the onerror function isn't called so don't know what the error is?
Can anybody see anything wrong with this?
Thanks, Steve
2 Answers
Hey Steve,
I would guess that it is because the response from your PHP server is not valid JSON.
Try setting your response headers at the very top of your PHP file: header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json');
and getting rid of these from your php file: echo $deviceId; echo "DB Connection made";
Change your while loop to this
while ($row=mysql_assocc($result)): $json[]=$row; endwhile; echo json_encode($json);
Your Answer
Think you can help? Login to answer this question!