0

Im using AJAX to request a php file that returns JSON

$.ajax({ url: 'php/invoice.php',
         dataType: "json",
         data: {id: 1},
         type: 'post',
         success: function(response) {
            alert(response);
         }
});

The php file im using is echoing json via json_encode:

while($row = mysqli_fetch_assoc($result))
{
   $queryResults[] = $row;
}
echo json_encode($queryResults);

an example of what the php is sending back is:

[{"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}]

What im getting when I alert(response) is "[object Object]"

What I want is to alert the first name or any other property in the json ie. "Brent"

Iv'e tried alert(response.firstname); and it returns as undefined.

iv'e also tried to remove the dataType: "json" from the ajax request and just parse the json when it gets returned via var obj = $.parseJSON(response) and alert(obj.firstname)

I dont know what im doing wrong, I also dont know why there [ ] around the json when I use json encode. Im assume its because its returning a array from json objects which may be my problem? Im new to this and would appreciate any help or resources!

Iv'e done a couple hours of research and still cant find a answer. Thanks in advance!

Brent Aureli
  • 463
  • 6
  • 21
  • 3
    The response is an **array** so you have to do `response[0].firstname`. Have a look at the question I linked to, it explains how to access (nested) arrays and objects. – Felix Kling Feb 23 '14 at 01:31
  • Thanks this solved it! Will take a look at that question, feels like I looked through a lot of questions but must have missed that one! Thx again. – Brent Aureli Feb 23 '14 at 01:40

2 Answers2

1

The problem lies here (as @echeese first pointed out)

while($row = mysqli_fetch_assoc($result))
{
   $queryResults[] = $row;
}
echo json_encode($queryResults);

Notice how the JSON looks (notice the [..] ?)

[{"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}]

It translates to this:

0 => {"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}

and you need to access it like this:

response[0].firstname
0

The problem that you're having is that your response is returning an array of objects. You should be able to get the first name by using response[0].firstname

Gray
  • 2,333
  • 1
  • 19
  • 24
  • Thanks! I thought I had tried every combination. But this solved it. Thanks much for the quest response. Will mark as answered as soon as it lets me! – Brent Aureli Feb 23 '14 at 01:38