Simplify and unify functions into one

Asked

Viewed 87 times

0

How can I simplify and leave everything in a single function the script below?

var plano_0 = new XMLHttpRequest();
    plano_0.open('GET', 'buscar_valor.php?id=10', false); 
    plano_0.send(null);
    plano_0=plano_0.responseText;
    plano_0_valor=plano_0.replace(".", ",")
    arrayAmount[0]=plano_0_valor;

var plano_1 = new XMLHttpRequest();
    plano_1 .open('GET', 'buscar_valor.php?id=20', false); 
    plano_1 .send(null);
    plano_1 =plano_0.responseText;
    plano_1_valor=plano_0.replace(".", ",")
    arrayAmount[1]=plano_1_valor;

var plano_2 = new XMLHttpRequest();
    plano_2.open('GET', 'buscar_valor.php?id=30', false); 
    plano_2.send(null);
    plano_2=plano_0.responseText;
    plano_2_valor=plano_0.replace(".", ",")
    arrayAmount[2]=plano_2_valor;

You could do it for example:

function buscaValor () {
var plano = new XMLHttpRequest();
    plano.open('GET', 'buscar_valor.php?id=id_do_array', false); 
    plano.send(null);
    plano=plano.responseText;
    valor=plano.replace(".", ",")
}

arrayAmount[0]=valor_id10;
arrayAmount[1]=valor_id20;
arrayAmount[2]=valor_id30;

Obviously the above function is wrong, but it’s just an example to show how it could be.

  • When using false in the plano.open you are saying that Ajax should be synchronous, IE, the code will only continue to be executed after a request reply. This is an unwelcome practice. Ajax must asynchronous, as is its nature.

1 answer

2


// Primeiro cria uma variável global, que será a array mestre
var planos;

// Daí você chama a função com os ids em array
// Exemplo: fazer_plano([10,20,30]);
// A função adiciona automaticamente os valores na variável planos
// Para recuperar é só usar: planos[0]

function fazer_plano(id) {
  for (i = 0; i < id.length; i++) {
    var plano = new XMLHttpRequest();
    plano.open('GET', 'buscar_valor.php?id=' + id[i], false);
    plano.send(null);
    planos.push(plano.responseText.replace(".", ","));
  }
}

Note: it is worth taking a look at the documentation of Xmlhttprequest because in your code there can be errors at runtime.

  • Very cool your tip, but I could not make it work. Is there any specific means to call the function with the ids? It got a little confusing this part for me

  • Yes, you call the function: fazer_plano([ID_NUMERO_UM, ID_NUMERO_DOIS])

  • I did it, but this giving: Typeerror: planes is Undefined

  • You put the line var planos; at the top of the page? in case there is still error try to initialize: var planos = [];

  • Now yes, it worked.. regarding your note, this code also has runtime errors?

  • Yes, you run the risk of not receiving the answer in time because of the connection, the best would be you use an event listener you have in Xmlhttprequest

  • Do you have a link where I can research this to try to implement this code?

  • Friend, you are already linked in the answer. but what you need is to implement the onreadystatechange of your Xmlhttprequest instance

  • Thank you, you know why I get this warning? XMLHttpRequest síncrono não deve ser usado na thread principal devido a seus efeitos prejudiciais para a experiência de usuário. Para mais informações http://xhr.spec.whatwg.org/

  • You have to put true on the last option of Xmlhttprequest, getting plano.open('GET', SEU_URL, true)

  • The warning is gone, but the function has stopped working, no longer loaded the values.

  • Did you implement onreadystatechange? For a look at this link, you have a very functional implementation: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange

  • I did the implementation, I sent you the code via chat to see how it turned out. He’s just carrying an ID, I couldn’t figure out why.

Show 9 more comments

Browser other questions tagged

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