Javascript: Array usage problem coming from php

Asked

Viewed 45 times

1

I am iterating with php and javascript and I have a problem. Javascript triggers the php file and receives the php array via json_encode. After that, I can read the array in Javascript, but I can’t use it for other treatments. Follow the codes:

var retorno;
var requisicao = new XMLHttpRequest();
requisicao.onload = reqListener;
requisicao.open("get", "../scr/farol_laudos_action.php", true);
requisicao.send(); 

function reqListener() {
    var dados = JSON.parse(this.responseText);
    retorno = dados;
};

alert(retorno[0]);

This way it is, it returns the blank page. What am I doing wrong? Thank you in advance!

2 answers

2

You are working with asynchronous functions, on account of that you should do all function treatment using promise or async await. The alert(retorno[0]) will not work because it is a synchronous variable, not an asynchronous state, for example.

You should study some asynchronous Javascript, as it is a slightly more complex subject and there is no quick way to deal with it without knowing a little about it. Here are some great articles to learn about:

Asynchronous Javascript: callbacks, Promises and async functions

Understanding async and await in Javascript

Understanding Promises once and for all

P.S.: Ajax (the Xmlhttprequest you are using) works asynchronously.

  • 1

    In the query itself it is possible to define whether to use it asynchronously or synchronously. httpRequest.open('GET', 'url', true); This last parameter defines whether the function is asynchronous or synchronous.

  • 1

    Eric Santana, thanks for the explanation! For the moment, I changed the parameter to false so that it works synchronously as mentioned, but I will study the asynchronous form. Thank you!

1


Apparently everything is right with your code, what I can notice will be just a parameter that you should pass different, follows the code snippet.

requisicao.open("get", "../scr/farol_laudos_action.php", true); 

This last parameter, if TRUE, your query will work asynchronously, ie will not wait for the return to assign the variable, in your case you want to assign to the variable and use this result, then you must change the parameter to FALSE, making the synchronous function, thus remaining.

requisicao.open("get", "../scr/farol_laudos_action.php", false); 

Reference : Ajax

Browser other questions tagged

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