0
$query = "SELECT Subjects FROM instructors";
$rows = mysqli_query($con,$query);
{
    if($rows)
    {
        $count = 0;
        while($row = mysqli_fetch_array($rows))
        {
            $id = 'Name'.strval($count);
            // array_push($results,$row);
            $results[] = array($id => $row['Subjects']);
            $count = $count + 1;
        }
        echo json_encode($results);
    }
    else
    {
        echo "Something wrong";
    }
}

This outputs

[{"Name0":"lore"},{"Name1":"ipsum"}]

Now in JS, I would like to get these names.

$(document).ready(function(){
$.ajax({
 url: "get_subs.php",
 dataType :"JSON",
 success : function(data)
 {
    alert(data);
 }
    })
});

But this only prints

0 => [object Object]

I also tried

alert(data.Name0);

But that also alerts the same thing. What am I doing wrong?

aandis
  • 4,084
  • 4
  • 29
  • 40
  • Use something like `console.log( JSON.stringify(data, null, 4) );` for readable output – kero Apr 27 '14 at 20:10
  • alert() is not a debugging tool, so your problem is trying to debug code with something that is meant for simple messages for the user. – adeneo Apr 27 '14 at 20:16
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Apr 27 '14 at 20:23

2 Answers2

0

The data is an array, so you need to access it by index:

alert(data[0].Name0);
Kong
  • 8,792
  • 15
  • 68
  • 98
0

Try JSON.stringify and see what it outputs. It's normal that when you alert something like an object or an array it outputs that.

alert(JSON.stringify(data));