I have been trying to fetch a json array from an external page. Even though it shows in the browser's element inspector, I can't use it in the console or in my code.
jquery code:
$.ajax({
type:"POST",
dataType:"json",
url:"datacenter.php",
success:function(data){
console.log(data.codeName);
},error:function(data){
console.log(data);
}
});
php code:
<?php header('Content-type: application/json'); ?>
insight = {
"code":"v34ns",
"codeName":["sureman","greatboy","namely"]
}
You need to do everything inside the php tags. You also need to echo json
<?php
header('Content-type: application/json');
//$ makes it a variable
$insight = array(
"code"=>"v34ns",
"codeName"=>["sureman","greatboy","namely"]
);
echo json_encode($insight);
?>
Now in your JS you need to parse the encoded json
$.ajax({
type:"POST",
dataType:"json",
url:"datacenter.php",
success:function(data){
console.log(data.codeName);
},error:function(data){
console.log(data);
}
});
console print data as string use json.parse() function
success:function(data){
var res = JSON.parse(data);
console.log(res.codeName);