Reputation: 165
i have this codes in my test.php that ajax send request from index.php to this page.in this page i created an array and convert it to json and returned it finally:
<?php
$arr = array(
"status"=>200,
"result"=>array(
"winner"=>"unknown",
"options"=>array(
"1"=>"first",
"2"=>"second"
),"question"=>"are u ok?",
"answer"=>"1"
)
);
$jsonArr = json_encode($arr);
echo $jsonArr;
?>
and in index.php i send request to test.php via ajax and i receive json . my problem is how can i alert just for example question from receive json from test.php.it alerts undefined
$.ajax({
type:'post',
url:'test.php',
data:{},
success:(function (response) {
var x = jQuery.parseJSON(response);
alert(x."question");
})
});
Upvotes: 0
Views: 2776
Reputation: 719
Try changing x."question"
to x.result["question"]
, or x.result.question
.
Everything is an object in JavaScript. You can dereference any object in JavaScript by using []
(bracket) notation. If there are no special characters in the name, you can omit the brackets and string and just do object.property
. Let's create an example.
let response = JSON.stringify({
status: 200,
result: {
winner: "unknown",
options: {
"1": "first",
"2": "second"
},
question: "are u ok?",
answer: 1
}
}); // Now response is almost exactly what you get from the server
console.log(response);
let x = JSON.parse(response);
console.log(x.result.question);
<p id="output"></p>
Upvotes: 3