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.

2
  • To resolve this, you can either use let address in support browsers or a closure function. 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. Commented Apr 30, 2016 at 19:49
  • Using a .forEach() instead of a loop would solve the problem too. Commented Apr 30, 2016 at 19:54

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Set request in object format, not string:

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

Second problem: alert server data instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.