I am testing the getJSON with php array, but it is not working, can anyone check for me ? I feel the problem is from the php code because when i test the html code with getJSON url https://graph.facebook.com/zombies, it is working.
In my array.php
<?php
header("Content-type: text/javascript");
$arr = array(
"name" => "Tim",
"age" => "28" );
echo json_encode($arr);
?>
In my test.html :
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
</head>
<body>
<script type='text/javascript'>
$(document).ready(function() {
$.getJSON('array.php', function(data) {
if(data) {
document.write(data.age);
}
else {
alert('error');
}
});
});
</script>
</body>
</html>
header("Content-type: text/javascript");
You're telling the browser you're sending it JavaScript, when what you're sending it is JSON. The content type for JSON is application/json
.
If you fix that, it should work, provided you're not running afoul of the Same Origin Policy. If you're making a cross-domain request, your options are:
Change
header("Content-type: text/javascript");
To
header('Content-Type: application/json');
For JSONP
header('Content-Type: application/javascript');
Try to set the content type to
application/json
So jQuery will interpte as json data