JSON return giving as undefinided in jQuery

Asked

Viewed 81 times

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 return.php file:

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

The return.php results in:

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

But in the jQuery, within the request ajax, both the data["nome"] as to the data["idade"] return undefinided. What might be going on?

1 answer

2


The navigation by the JSON object takes place with point, ie to access the value of nome, you must use data.nome.

Also, I suggest to clarify that you expect a JSON as 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);
    }
})
  • It’s irrelevant to use data["nome"] or data.nome, "Navigation by JSON object occurs with dot" is not 100% correct. The problem here was to add dataType: 'json', for the ajax to return an object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.