0

I post here a snippet of code where I get a runtime error. The variable x changes is value inside an ajax call:

$("#acquisto").click(function(){
            var x = 0;
            for(x = 0; x < numRighe; x++){
                if( $("#ch"+x).prop("checked") == true){
                    alert("#tr"+x);
                    $.ajax({
                          url:"eliminazioneRecord.php",
                          type: "GET",
                          data: { Codice: $("#ch"+x).val() },
                          success:function(result){
                            //$("#tr"+x).fadeOut("slow");
                            alert("#tr"+x);
                        },
                          error:function(richiesta,stato,errori){
                            alert("<strong>Chiamata fallita:</strong>"+stato+" "+errori);
                        }
                    });
                }
            }
        });

I realized that because the in the alert before the ajax call x has a value that is different from the one showed in the alert inside the success function. Where I am wrong?

giacomotb
  • 607
  • 4
  • 10
  • 24

2 Answers2

1

All the anonymous functions passed to success in $.ajax reference the same x variable from the outer scope which is incremented by the for structure. You need each function to have it's own copy of x.

success:function(copy_x) {
  return function(result){
    //$("#tr"+copy_x).fadeOut("slow");
    alert("#tr"+copy_x); 
  }
}(x),
Tibos
  • 27,507
  • 4
  • 50
  • 64
0

It is because your are using the loop variable x in a closure within the loop.

$("#acquisto").click(function () {
    for (var x = 0; x < numRighe; x++) {
        (function (x) {
            if ($("#ch" + x).prop("checked") == true) {
                alert("#tr" + x);
                $.ajax({
                    url: "eliminazioneRecord.php",
                    type: "GET",
                    data: {
                        Codice: $("#ch" + x).val()
                    },
                    success: function (result) {
                        //$("#tr"+x).fadeOut("slow");
                        alert("#tr" + x);
                    },
                    error: function (richiesta, stato, errori) {
                        alert("<strong>Chiamata fallita:</strong>" + stato + " " + errori);
                    }
                });
            }
        })(x)
    }
});

Read:

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531