Return JSON giving as undefinided in jQuery

1

I have this ajax request:

$.ajax({
    type: "POST",
    url: "retorno.php",
    success: function(data){
        alert(data["nome"]);
    },
    error: function(erro){
        alert(erro);
    }
})

And the file return.php:

<?php 
    $teste=array();
    $teste["nome"]="nometeste";
    $teste["idade"]="aa";
    $a=json_encode($teste);
    echo $a;
?>

Returns.php results in:

{
    "nome":"nometeste",
    "idade":"aa"
}

But in jQuery , within ajax , both data["nome"] and data["idade"] return undefinided . What could be happening?

    
asked by anonymous 29.02.2016 / 13:11

1 answer

2

The navigation by the JSON object is done with a point, that is, to access the value of nome , you should use data.nome .

In addition, I'd like to make it explicit that you expect a JSON as a return, with the parameter dataType: 'json' :

$.ajax({
    type: "POST",
    url: "retorno.php",
    dataType: 'json',
    success: function(data){
       alert(data.nome);
    },
    error: function(erro){
       alert(erro);
    }
})
    
29.02.2016 / 13:48