Reputation: 55
My php code is as below
if ($data = $user->fetch())
{
echo json_encode(array("output" => $data));
}
else
{
echo json_encode(array("output" => $data));
}
My javascript code is as below
success: function(response)
{
alert(response); //shows me [object Object]
alert(response[0].output); // shows me nothing
alert(response[0]); //shows me undefined
alert(JSON.stringify(response)); //shows me {"output":false}
//I would like to get only true or false
}
From this post (jQuery AJAX call returns [object Object]) I knew that [object Object] is basically an array.
From this post (jQuery Ajax: get specific object value) I got below words.
"As you can see your response starts with [ and ends with ]. So your response is an array.
Then, inside the array, you get objects (starting with { and ending with }).
So your data is an array, which can be accessed with data[x] (x being the index), and each member of the selected object can be accessed with the .dot notation: .word, .text etc.
So in your case, if there's only one result, you can do data[0].word."
In this case I should get my expected result using alert(response[0].output);
But I am not getting that result. Can anyone help me in this regard ??
Upvotes: 0
Views: 4606
Reputation: 79
You can try also this one:
success: function(response) {
// check your console
console.log(response);
//this two will give you same result
console.log(response.output);
console.log(response['output']);
//either of this two
var output = response.output;
var output = response['output'];
if(output){
//code here
}
}
Upvotes: 0
Reputation: 41885
First off, make sure that you have explicitly set that you're going to receive JSON:
dataType: 'JSON',
Then try to access them thru this instead:
success: function(response) {
console.log(response.output);
// kindly open your console browser to see contents
// i think this is F12
if(response.output) {
// do something if true
} else {
// do something if false
}
}
Upvotes: 1