JSON returning Undefined value

Asked

Viewed 499 times

0

Guys, I have a code where I receive JSON data, but when I show it is as Undefined.

function usuario_search(id){  $.ajax({
type:"GET",
url: "/usuarios/search/"+id,
success: function(data) {
        console.log(data);
        var json = JSON.parse(data);
        console.log(json);
        alert(data);
        document.getElementById('name').value = json.name;
        document.getElementById('email').value = json.email;
        document.getElementById('permission').value = json.role;
        $('#defaultModal').modal('show');
      },
      error: function(ts){
        $("#error").text(ts.responseText);
      }});}

Alert with the data:

inserir a descrição da imagem aqui

What appears in the modal:

inserir a descrição da imagem aqui

Debugger:

inserir a descrição da imagem aqui

  • puts a Debugger; and sees the return, depending on how it was done on the server it comes as return.data in your case would be date.

  • edited the publication, look there

  • You have noticed that json is an array?

  • 1

    tried document.getElementById("name").value = json[0].name; ?

  • 1

    @Leonardobosquett Thank you so much! I got it, I’m starting Ajax, but thank you so much.

1 answer

0


The problem is because the json variable is an array: To access the values you need to access the index first, for example:

var json = [ 
    { 
        "email": "[email protected]",
        "name": "Admnistrador",
        "role": "Administrador"
    }
];
console.log(json[0].name);

Note

If you intend to use only 1 user, no need to return in array; also nay recommend to use in the code the direct access to the index json[0].name . This is just an example of how you can get the value with the current json

Browser other questions tagged

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