JSON returning value undefined

0

Well, I have a code where I get the JSON data, but the display is 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 data:

Whatappearsinthemodal:

debugger:

    
asked by anonymous 31.07.2018 / 13:17

1 answer

0

The problem occurs because the json variable is an array: To access the values it is necessary 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 no I recommend using direct index access json[0].name in code. This is just an example of how you can get the value with the current json

    
31.07.2018 / 13:38