Question

I'm trying to run a simple getJSON to a PHP file using:

$.getJSON("loadThumbs.php", { usrID: 25 }, function(data){
  alert(data.filename);
  });

And when the alert messages pops up it reads "undefined."

Here's my PHP file (loadThumbs.php):

$usrID = $_GET['usrID'];

$sql = "SELECT id, isDefaultProfile, filename, usrID FROM profile_images WHERE   isDefaultProfile=1 AND usrID='$usrID'";
$result = mysql_db_query($DBname,$sql,$link) or die(mysql_error()); 

$rows = array();

while($r = mysql_fetch_assoc($result)) {
   $rows[] = $r;
 }
print json_encode($rows);

//Which outputs: [{"id":"5","isDefaultProfile":"1","filename":"26.jpg","usrID":"25"}]

Any ideas on what I might be doing wrong?

Was it helpful?

Solution

Try:

alert(data[0].filename);

The JSON being returned is an array (the brackets) containing one object (the curly braces), so you have to access the first element of the array to be able to get the filename of the first file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top