I have a array on test.php
like this .
Array(
[0] => Array
(
[id] => 1
[name] => nikhil
[password] => 81dc9bdb52d04dc20036dbd8313ed055
)
[1] => Array
(
[id] => 2
[name] => akhil
[password] => 81dc9bdb52d04dc20036dbd8313ed055
)
)
I convert it into JSON and echo it
$jsonformat = json_encode($array);
echo $jsonformat;
Then I get a JSON string like this on test.php
[{
"id": 1,
"name": "nikhil",
"password": "81dc9bdb52d04dc20036dbd8313ed055"
},{
"id": 2,
"name": "akhil",
"password": "81dc9bdb52d04dc20036dbd8313ed055"
}]
Now how can I access this string as JSON using an AJAX call. I want to access only name of 1st row of this JSON object. I tried this:
$.ajax({
type: 'post',
url: '/test.php',
datatype: 'JSON',
success: function(result) {
alert(result[0].name);
}
});
But this is not working. Any suggestions?
Javascript is case sensitive. You set the data type to json
so that jQuery knows what to expect back and parse it automatically.
However, the correct key for the data type is dataType
and not datatype
.
So you need:
$.ajax({
type: 'post',
url: '/test.php',
dataType: 'JSON',
success: function(result) {
alert(result[0].name);
}
});