Beqa
Beqa

Reputation: 99

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.

Upvotes: 0

Views: 55

Answers (2)

dYale
dYale

Reputation: 1661

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);
}

Upvotes: 2

Set request in object format, not string:

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

Second problem: alert server data instead.

Upvotes: 0

Related Questions