cs-smith cs-smith - 3 months ago 8
Ajax Question

json array returns, but can't use the response to access it

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"]
}

Answer

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){
        var obj = JSON.parse(data);
        console.log(obj.codeName);
    },error:function(data){
        var obj = JSON.parse(data);
        console.log(obj);
    }
});
Comments