-1

PHP: lockState.php

require '../dbconn.php';
$query = mysql_query("select id, lockState,name from register_db where Id=1");
$items = array();
while ($row = mysql_fetch_object($query)) {
    array_push($items, $row);
}
echo json_encode($items);

Result from query

[{"id":"1","lockState":"No","name":"Local Application"}]

Index.php

$.ajax({
            type: "POST",
            url: "feed/lockState.php",
            data: ({id: 1}),
            cache: false,
            dataType:"json",
            success: function (response) {
                alert(JSON.stringify(response));  // [{"id":"1","lockState":"No","name":"Local Application"}]
                alert(response.name); //***undefined***
                  if(response.name=='Local Application'){
                     callMyFunction(response.name);
                   }
          },
            error: function () {
               alert("Oops..!! Something wrong!);

            }
        });

I'm totally lost where I'm doing wrong in using 'Success' response. Even I tried to JSON.parse(response) and tried to access the key:value, but still same undefined. Please help.

Mr.Kiran
  • 79
  • 1
  • 1
  • 9
  • 1
    because it is an array, not an object. – epascarello Nov 16 '16 at 13:45
  • 1
    `response` is an array – adeneo Nov 16 '16 at 13:45
  • In situations like this, you can do `console.log(response)` to get a nice representation of the variable in the error console. – Pekka Nov 16 '16 at 13:46
  • **Warning**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) which has been **removed** entirely from the latest version of PHP. You should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Quentin Nov 16 '16 at 13:47
  • Hello Quentin, Yes I'm using the latest version, however it was a old application still in use which will we are working to replace it. – Mr.Kiran Nov 16 '16 at 13:54

3 Answers3

2

response[0].name will help you.

Dhaval Soni
  • 205
  • 2
  • 14
2

Look at your PHP. See $items = array(); where you create an array.

Look at the data you are getting. See the [ and ] around it.

You have an array containing an object. You need to read the first value out of that array.

var object = response[0];
var name = object.name;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

The way you tried would work if the response was:

{"id":"1","lockState":"No","name":"Local Application"}

But your response is:

*[*{"id":"1","lockState":"No","name":"Local Application"}*]*

The brackets mean the response is an array, [], containing an object, {};

As others have mentioned; the way to retrieve values out of an array can be done by using array_variable[0] to for example select the first.

In your example try this:

 alert(response[0].name); //***undefined***
Olaf
  • 1,038
  • 8
  • 20