Array is not preserved after AJAX

0

I have the following AJAX function that runs within for to check if certain data exist or not, if there is one variable is increased by one, if not, another variable is increased in one:

 si = 0;
 no = 0;
for (var j = 1; j < parseInt(totalCajas); j++) {

     $.ajax({
            url: "views/ajax/OIT.php",
            method: "GET",
            data: { funcion: "funcion7", lote: valorLote, caja: j },
            async: false,
            dataType: "json",
            success: function(respuesta1) {
                     if (respuesta1.length == 0) {
                        no++;
                        } else {
                            si++;
                            arrayHay[si - 1] = j;
                            console.log("Local hay: ", arrayHay[si - 1]);
                        }

            }
      });
}
console.log("Cajas donde hay algo: ", si);
console.log("Cajas donde no hay algo: ", no);
console.log("Donde hay algo: ", arrayHay);

The question is that the data of si and no are preserved, not so the array There is, even shows it within if of si with line c onsole.log("Local hay: ", arrayHay[si - 1]) ; but already out in the last line of the example here put no data, what would be the mistake I'm making?

Thanks

    
asked by Baker1562 25.02.2018 в 21:58
source

1 answer

2

The problem you're facing is called context.

The array must be declared on the same level as your% si and no

variable
si = 0;
no = 0;
var arrayHay = [];

In this way, when you do the printing at the end, you will have modified your original variable. If that variable is only declared within the closure of success, it will only be known within that context, if not.

    
answered by 25.02.2018 / 22:58
source