0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Beqa
  • 101
  • 2
  • 14
  • To resolve this, you can either use [`let address`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) in support browsers or [a closure function](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). The reason: `var address` only exists once for the entire loop and, because `$.get()` behaves asynchronously, `alert(address);` isn't evaluated until after the `for` loop is done and has reassigned `var address` multiple times. – Jonathan Lonowski Apr 30 '16 at 19:49
  • Using a `.forEach()` instead of a loop would solve the problem too. – Pointy Apr 30 '16 at 19:54

2 Answers2

2

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);
}
dYale
  • 1,541
  • 1
  • 16
  • 19
0

Set request in object format, not string:

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

Second problem: alert server data instead.

József Cserkó
  • 299
  • 2
  • 9