Problem trying to use JSON values - Javascript

Asked

Viewed 34 times

2

Well I have the following javascript code inside a function called query() that receives the value index 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 variable Resp for Resp.name or Resp.size the value of the variable becomes Undefined.

  • This function is called asynchronously soon the return makes no sense. But take advantage and also put the code where you are trying to change the value of resp.nome

  • I’m not trying to change the value, just display it. When I use console.log(resp) the value returned is a JSON but when use console.log(resp.nome) the value returned is Undefined. And thanks for the notice about the Returns.

1 answer

0


You need to convert the return of Ajax to JSON object. At the moment it is only one string. Use the method JSON.parse(). Change:

resp = request.response;

For:

resp = JSON.parse(request.response);

Also remove the return resp; unnecessary.

Method documentation.

Browser other questions tagged

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