Reputation: 29
In my php file I have:
$arr[] = array("status"=>0);
echo json_encode($arr);
In my javascript, I have:
$(document).ready(function(){
initialize();
$("#searchbutton").click(function(){
var usrinput = $("#userinput").val();
$.get(
"searchpageajaxjson.php",
{searchterm: usrinput},
function(data){
searchreturned(data);
},
"json"
);
});
});
function searchreturned(data){
console.log(data);
var parsed = jQuery.parseJSON(data);
console.log(parsed);
//for (var i = 0; i < parsed.length; i++) {
// alert(parsed[i]);
// }
//
}
The console.log(data) shows [object Obejct] and console.log(parsed) shows null
Where am I going wrong?
Edited to Add:
alert(data.status) shows undefined.
Second Edit:
I'm really grateful for all the help I've received. It's hard to pick an answer, because I'm really only able to move on from this problem due to all the help received in all the comments. I am always in awe of you kind folks who give your time to helping newbies like myself.
Upvotes: 2
Views: 1213
Reputation: 14187
1. There is no reason to call jQuery.parseJSON
or $.parseJSON
because jQuery knows that is already a JSON object due to the "json"
parameter you passed here:
$.get('source', {param:param}, function(data){ /*work with data*/ }, "json");
2. If console.log(data);
is not null and you are getting some [Object Object]
try to see what are the properties of that object, like this:
e.g: Explore your object:
e.g: Print value from object:
//this will output "Horror"
data.genre
Hope this helps you.
Upvotes: 1
Reputation: 225124
You're not supposed to call jQuery.parseJSON
on data
again. jQuery takes care of that for you already, since you used "json"
as the dataType
.
Upvotes: 2