0

I created json with php. Data coming with ajax. But JSON.parse is giving an “undefined” object. Why ?

Php CODE

 $emparray = array();
 while($row =mysqli_fetch_assoc($result))
 {
     $emparray[] = $row;
 }

 echo json_encode($emparray);

Ajax CODE

   $.ajax({
        type: "GET",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= JSON.parse(msg);
            alert(obj.name);// giving undefined
        },
        error: function (error) {
        }
    });

json

[{"name":"eng","a":"sdf"}]
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Engineer23
  • 55
  • 1
  • 8
  • 2
    because you have an array that has an object in the first index. `obj[0].name` – epascarello Dec 06 '17 at 13:45
  • 1
    obj is an array, try accessing the first element. `obj[0].name` – ztadic91 Dec 06 '17 at 13:45
  • 4
    Please, [quit using `alert()` for troubleshooting.](http://stravid.com/en/stop-the-javascript-alert-madness/), use `console.log()` instead. – Jay Blanchard Dec 06 '17 at 13:45
  • If an answer solved your problem, consider accepting the answer. Here's how http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work then return here and do the same with the tick/checkmark till it turns green. This informs the community, a solution was found. Otherwise, others may think the question is still open and may want to post (more) answers. You'll earn points and others will be encouraged to help you. *Welcome to Stack!* – Jay Blanchard Dec 06 '17 at 14:10

3 Answers3

1

You should obj[0].name

Because you are accessing the name property of the of the first element of the array.

Eddie
  • 26,593
  • 6
  • 36
  • 58
1

Your JSON is an array, meaning you'll have to point to the index of the object before accessing the property.

This code should work:

console.log(obj[0].name); //Returns "eng"

If your JSON array was something like this:

[{"name":"eng","a":"sdf"}, {"name":"esp", "a":"abc"}]

Then obj[1].name would return "esp".

chrisv
  • 724
  • 6
  • 18
0

A better way to get data from server

$emparray = array();
 while($row =mysqli_fetch_assoc($result))
 {
     $emparray[] = $row;
 }

 echo json_encode(array("data"=>$emparray));

Put all the json response on a key which is data here then at front end define that the server response is in JSON by dataType and then there is no need to parse data by JSON.parse()

msg.data.length will provide you the validaton on if the data received from server is empty or not which will prevent the undefined error

 $.ajax({
        type: "GET",
        dataType: "JSON",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= msg.data;
           if(msg.data.length){       
                  alert(msg.data[0].name);// wll give name at 0 index
              }
        },
        error: function (error) {
        }
    });
Meenesh Jain
  • 2,532
  • 2
  • 19
  • 29