Problem when trying to use values from a JSON - Javascript

2

I have the following javascript code inside a function called query () that receives the index value of an input:

var request = new XMLHttpRequest();

if (!request) {
    alert('Que pena :( a requisição não pode ser feita');
}else{

    request.onreadystatechange = resposta;
    request.open('GET', 'query.php?busca='+index);
    request.send();
}


function resposta() {
    if (request.readyState === XMLHttpRequest.DONE) {
        if (request.status === 200) {
            console.log(request.response);

            document.getElementById('nome').innerHTML = request.response;
            document.getElementById('tamanho').innerHTML = request.response;

            resp = request.response;
            console.log(resp);
            return resp;

        } else {
            return 'Problema na requisição';
        }
    }
}

The function receives a JSON like this from a PHP code:

  

{"name": "fish", "size": "30"}

But when I change the resp variable to resp.name or resp.Status variable value becomes undefined.

    
asked by anonymous 17.03.2018 / 02:55

1 answer

0

You need to convert Ajax's return to JSON object. At the moment it is just a string . Use the JSON.parse() method. Change:

resp = request.response;

By:

resp = JSON.parse(request.response);
  

Also remove% unnecessary%.

Method documentation.

    
17.03.2018 / 14:50