Reputation: 415
So I have to files. A javascript file that is making an AJAX request to a PHP file that is suppose to return JSON. I have tested the PHP file with a print statment and there is definetly JSON being made. However in javascript the request.responseText is empty.
Javascript:
var mCurrentIndex = 0;
var request = new XMLHttpRequest();
var mImages = [];
var json;
var url = "fiveMostRecent.php";
request.open("GET", url, true);
request.send();
request.onreadystatechange = function(e)
{
if(request.readyState == 4 || request.readyState == 2){
console.log(request.responseText);
json = JSON.parse(request.responseText);
console.log(json);
for(var x = 0; x < json.length; x++){
var gImage = new GalleryImage();
gImage.title = json[x].title;
gImage.price = json[x].price;
gImage.description = json[x].description;
gImage.img = new Image();
gImage.img.src = json.images[x].imgPath;
makeGalleryImageOnloadCallback(gImage);
mImages.push(gImage);
}
}
console.log(mImages);
}
PHP:
<?php
session_start();
$con = mysql_connect("localhost", "listAdmin", "hermes");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("GregsList", $con)
or die("Unable to select database:" . mysql_error());
$query = "SELECT title, description, price FROM Listings ORDER BY dateListed DESC LIMIT 5";
$result = mysql_query($query);
#converts to json
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
#print json_encode($rows);
return json_encode($rows);
?>
Upvotes: 0
Views: 373
Reputation: 22711
Use echo json_encode($rows);
instead of return json_encode($rows);
Upvotes: 2