1

Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

i have a javascript which does a XMLHttp request to a php file, which in turn queries a mysql table and returns a JSON array... but somehow i cannot access individual elements of the array. here is the javascript:

<script type="text/javascript">
function show(){
    if(window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange= function () {
        if(xmlhttp.readyState==4 && xmlhttp.status==200){

            var response= new Array();
            response=xmlhttp.response;
            alert(response);
        }
    }
    xmlhttp.open('GET','test.php', true);
    xmlhttp.send();

}
</script>

and this is the php script:

mysql_select_db('testpolaroid') or die ('Unable to select database!');
$query = 'SELECT * FROM images';
$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
if(mysql_num_rows($result) > 0)
{
    $row = mysql_fetch_assoc($result);
    echo json_encode($json);
}

the response that i get is :

 {"imageid":"11","location":"11.jpg"}
Community
  • 1
  • 1
harsha
  • 13
  • 4
  • 3
    Welcome to Stack Overflow! [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – Madara's Ghost Jan 19 '13 at 11:37
  • `json array in javascript` seems a little redundant as json means `javaScript object notation`. – Igor Parra Jan 19 '13 at 11:44
  • @NomikOS It's not redundant. JSON is a data format (like XML) and it needs to be parsed (like with an XML parser) before its contents can be used. – Mattias Buelens Jan 19 '13 at 11:51
  • @mattias-buelens OK, OK. But still **seems**. I mean that question could be better understood as `how to read a json string in javascript` instead `how to use json array in javascript`. Peace. – Igor Parra Jan 19 '13 at 12:04

1 Answers1

3

You need to parse the JSON first with JSON.parse, code would look like:

var response = JSON.parse(xmlhttp.responseText);
var imageid = response["imageid"];
Overv
  • 8,433
  • 2
  • 40
  • 70