I am having trouble trying to return results from a PHP script, back into my HTML / Jquery application.
Currently, I am trying to connect to the server like so:
function getDatabaseRows()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "myDomain.com/subDirectory/getRowCounts.php", true);
xmlHttp.send(null);
}
With my response handler being:
function HandleResponse(response)
{
alert(response.length);
if(response.length != 0)
maxArray = JSON.parse(response);
storage.set('currentID', maxArray);
}
Currently, whenever I run the code, getDatabaseRows()
always ends up calling HandleResponse(response)
. The problem is that response.length
always equals 0
.
The PHP script is simply collecting the maximum row count from the database and returning the row counts:
<?php
$rowCounts = [];
$dbhost = 'host';
$dbuser = 'host';
$dbpass = 'host';
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db("host") or die(mysql_error());
$sql = "SELECT MAX(TID) AS MaxTID FROM TransData";
$results = mysql_query($sql, $con);
$transRow = mysql_fetch_array($results);
$maxTrans = $transRow['MaxTID'];
$sql = "SELECT MAX(FID) AS MaxFID FROM FullData";
$results = mysql_query($sql, $con);
$fullRow = mysql_fetch_array($results);
$maxFull = $fullRow['MaxFID'];
$sql = "SELECT MAX(SID) AS MaxSID FROM SalamanderData";
$results = mysql_query($sql, $con);
$salamanderRow = mysql_fetch_array($results);
$maxSal = $salamanderRow['MaxSID'];
$sql = "SELECT MAX(OID) AS MaxOID FROM OthersData";
$results = mysql_query($sql, $con);
$othersRow = mysql_fetch_array($results);
$maxOther = $othersRow['MaxOID'];
array_push($rowCounts, $maxTrans, $maxFull, $maxSal, $maxOther);
echo json_encode($rowCounts);
mysql_close($con);
?>
When I point my browser directly to the script, it echo's the row counts correctly for me. I am only having trouble trying to get data through AJAX.
EDIT:
Ok, I finally got the script connected, it had something to do with Cross-Domain scripting problems. All sorted out now.
New problem though:
function HandleResponse(response)
{
if(response.length != 0)
maxArray = JSON.parse(response);
storage.set('currentID', maxArray);
}
HandleResponse throws an error when parsing the JSON Error trying to parse '<'
, So I assume that it has something to do with the way that Array was encoded. How do I go about troubleshooting this problem and figuring out how to parse that array?