Update object values via GET without repetition

Asked

Viewed 74 times

1

To working on a plane table, which has a script with multiple objects, thus:

var plano_basicoUS = { 
    1: null, // mensal
    2: null, // trimestral
    3: null, // semestral
    4: null, // anual
};

var plano_economicoUS = { 
    1: null, // mensal
    2: null, // trimestral
    3: null, // semestral
    4: null, // anual
};

I update the values of each one via $.get, thus:

$.get("buscar_valor.php?id=3&periodicidade=monthly", function(resultado){
    plano_basicoUS[1] = parseFloat(resultado);
});
$.get("buscar_valor.php?id=3&periodicidade=quarterly", function(resultado){
    plano_basicoUS[2] = parseFloat(resultado);
});
$.get("buscar_valor.php?id=3&periodicidade=semiannually", function(resultado){
    plano_basicoUS[3] = parseFloat(resultado);
});
$.get("buscar_valor.php?id=3&periodicidade=annually", function(resultado){
    plano_basicoUS[4] = parseFloat(resultado);
});

$.get("buscar_valor.php?id=4&periodicidade=monthly", function(resultado){
    plano_economicoUS[1] = parseFloat(resultado);
});
$.get("buscar_valor.php?id=4&periodicidade=quarterly", function(resultado){
    plano_economicoUS[2] = parseFloat(resultado);
});
$.get("buscar_valor.php?id=4&periodicidade=semiannually", function(resultado){
    plano_economicoUS[3] = parseFloat(resultado);
});
$.get("buscar_valor.php?id=4&periodicidade=annually", function(resultado){
    plano_economicoUS[4] = parseFloat(resultado);
});

Each query of $.get returns a value like: 10.00, through the PHP file.

As there are several objects, I would not have to repeat the gets for each one.

How can I do this dynamically, noting that each $.get has a different URL? Or sequentially, if applicable.

2 answers

1


Create an array object where you can take the object name and the id that varies from one to the other:

var valores = [
   {plano: "plano_basicoUS", id: 3},
   {plano: "plano_economicoUS", id: 4}
];

Then create a function to loop up to the limit of item numbers in the array, doing a sublooping 4 times (amount of object values) by calling the same function whenever a $.get is completed.

You don’t even need to create the objects plano_basicoUS and plano_economicoUS manually, the function already creates them dynamically:

The code would look like this:

var valores = [
   {plano: "plano_basicoUS", id: 3},
   {plano: "plano_economicoUS", id: 4}
];

var contagets = 0;
var contavalores = 1;
function carregaObjs(){
   if(contavalores <= valores.length*4 && contagets < valores.length){

      if(contavalores == 1){
         var periodo = "monthly";
      }else if(contavalores == 2){
         var periodo = "quarterly";
      }else if(contavalores == 3){
         var periodo = "semiannually";
      }else if(contavalores == 4){
         var periodo = "annually";
      }

      var urL = 'buscar_valor.php?id='+valores[contagets].id+'&periodicidade='+periodo;

      $.get(urL, function(resultado){

         //cria os objetos de forma automática
         if(!window[valores[contagets].plano]){
            window[valores[contagets].plano] = {};
         }

         window[valores[contagets].plano][contavalores] = parseFloat(resultado);

         if(contavalores == 4){
            contavalores = 1;
            contagets++;
         }else{
            contavalores++;
         }

         carregaObjs();
      }); 
   }
}

carregaObjs();
  • All right, I just couldn’t get them to charge, just like that flame() function you had me on.

  • I made a change that creates the objects automatically.

  • On the question of function chama, you don’t even need to put a value, already automatic grip: function chama(){&#xA; if(contagets == valores.length-1){&#xA; $("select.periodicidades").trigger('change');&#xA; }&#xA;}

  • And you call the function chama(); within $.get before that if: if(contavalores == 4){.

  • It worked, but only loaded the foreground values.

  • Have a look at the source code: http://dvdteste.hostgemdesites.ws/teste.php

  • Oh yes, I had put in the wrong place the chama();. How would it be for him to load the values together with the page loading?

  • The answer has. Just call the function carregaObjs();

  • Something like that? $(document).ready(function () {&#xA; carregaObjs();&#xA;});

  • In this case it would not be necessary to call() the function right? because it will load the whole function.

  • When adding more items need to update some value? Because I put 5 select, and it didn’t work. I updated tbm values in: var valores and of the initial objects.

  • No, it’s all automatic. You just need to add in the array valores.

  • Take away one more doubt?

  • can help me update the script to display the coin value with mile score?

Show 10 more comments

1

Use arrays to easily iterate and simplify code. In these cases it’s good to find patterns to simplify.

An example would be:

const periodicidade = ['mensal', 'trimestral', 'semestral', 'anual'];

const promisesPlanoBasico = periodicidade.reduce((promises, periodo) => {
  const nextPromise = $.get(`buscar_valor.php?id=3&periodicidade=${periodo}`);
  return promises.concat(nextPromise);
}, []);

const promisesPlanoEconomico = periodicidade.reduce((promises, periodo) => {
  const nextPromise = $.get(`buscar_valor.php?id=4&periodicidade=${periodo}`);
  return promises.concat(nextPromise);
}, []);

Promise.all([
    Promise.all(promisesPlanoBasico), Promise.all(promisesPlanoEconomico)
  ])
  .then(([plano_basicoUS, plano_economicoUS]) => {
    plano_basicoUS = plano_basicoUS.map(str => parseFloat(nr));
    plano_economicoUS = plano_economicoUS.map(str => parseFloat(nr));

    // aqui podes usar os valores que foste buscar
  })
  .catch(err => console.log(err));

You can compress/optimize the code further if needed. It could look like this for example:

const promises = ['mensal', 'trimestral', 'semestral', 'anual'].reduce((promises, periodo) => {
  promises[0].push($.get(`buscar_valor.php?id=3&periodicidade=${periodo}`));
  promises[1].push($.get(`buscar_valor.php?id=4&periodicidade=${periodo}`));
  return promises;
}, [[], []]);

Promise.all(promises.map(Promise.all))
    .then(([plano_basicoUS, plano_economicoUS]) => {
      plano_basicoUS = plano_basicoUS.map(str => parseFloat(nr));
      plano_economicoUS = plano_economicoUS.map(str => parseFloat(nr));

      // aqui podes usar os valores que foste buscar
    })
    .catch(err => console.log(err));

Browser other questions tagged

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