Beqa Beqa - 7 months ago 14
Javascript Question

Jquery $.get() passing a variable issue

I can't pass different values of variable through $.get() function
please check this code to learn more about my problem

var addressFieldValues = ['address1', 'address2', 'address3'];

for(i=0; i<addressFieldValues.length; i++) {
var address = addressFieldValues[i];
$.get('function.php', address, function(data){
alert(address); // alerts address1 all time
});
}


Why is it alerting "address1" these 3 times? since it should alert 3 different addresses at all :(.

Thank you guys in advance ;), please help me, this is so urgent...

Answer

One option would be to wrap your get request in a function, and pass in address as an argument. This way, you avoid the asynchronous issues.

function get(address) {
    $.get('', address, function(data) {
        alert(address);
    });
}

var addressFieldValues = ['address1', 'address2', 'address3'];
for (i = 0; i < addressFieldValues.length; i++) {
    var address = addressFieldValues[i];
    get(address);
}