save variable value JQUERY

0
$.ajax({
        url: 'https://swapi.co/api/people/?format=json',
        type:'GET',
        dataType: 'JSON',
        success: function(per){
            var film;
            for (var i = 0; i < 6; i++) {
                for (var index = 0; index < 3; index++) {
                    var ul = per.results[i].films[index];
                    $.ajax({
                        url:ul,
                        type: 'GET',
                        dataType: 'JSON',
                        success:function(res){
                            film += "hgagagg";
                            console.log(film);
                        }
                    }); 
                }

                var a = $("<div data-toggle='modal' data-target='#myModal' onclick=\"data2('"+film+"')\" class='col-md-4'>" + per.results[i].name + "</div>");
                $(".row").append(a);
                console.log(per.results[i].name);
            }
        }
    });
});

The problem is that when I send the film parameter in the Onclic function, the variable film has the value of the beginning and not the one that has within the function success

    
asked by Ernesto Emmanuel Yah Lopez 16.10.2017 в 10:55
source

1 answer

2

A simple solution is to have a response counter. When the counter reaches 18, you create the div:

const ITERACIONES_1=6;
const ITERACIONES_2=3;
let helper= {
  film:'',
  counter:0,
  method: function (res) {
    this.film += 'loquesea';
    this.counter++;
    if (this.counter == (ITERACIONES_1 * ITERACIONES_2) {
      var a = $("<div data-toggle='modal' data-target='#myModal' " + 
        "onclick=\"data2('"+this.film+"')\" class='col-md-4'>" +
        per.results[i].name + "</div>");
      $(".row").append(a);
      console.log(per.results[i].name);
    }
  }
};

$.ajax({
        url: 'https://swapi.co/api/people/?format=json',
        type:'GET',
        dataType: 'JSON',
        success: function(per){
            var film;
            for (var i = 0; i < ITERACIONES_1; i++) {
                for (var index = 0; index < ITERACIONES_2; index++) {
                    var ul = per.results[i].films[index];
                    $.ajax({
                        url:ul,
                        type: 'GET',
                        dataType: 'JSON',
                        success:function(res){
                            helper.method(res);
                        }
                    }); 
                } 
            }
        }
    });
});
    
answered by 16.10.2017 в 12:02