1

Here is a sample of my code, i've removed the unnecessary parts. I've set a global variable recipient. It should be alert 1 but nothing is being alerted. What is the correct way to change a variable set outside a function? How do i solve this?

var recipient = 0;

$("#submit-button").click(function () {

    $.getJSON("/fetch.php?o=4&user=" + k, function (B) {
        $.each(B, function (index, result) {
            recipient = 1;

        })

    })

    if (recipient == 1) {
        alert("yes");
    }
})
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
user892134
  • 3,078
  • 16
  • 62
  • 128
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – James Montagne Jul 03 '13 at 18:15

2 Answers2

4

It is due to asyn call, put the condition in callback function instead of putting if after it. The call back is called after the click function finished execution.

var recipient = 0;      


$("#submit-button").click(function() {

  $.getJSON("/fetch.php?o=4&user=" + k, function(B) {
       $.each(B, function(index, result) {
            recipient = 1;    
       });
      if(recipient==1) {
         alert("yes");
      }
   });
});
Adil
  • 146,340
  • 25
  • 209
  • 204
1

You're checking to see if recipient is 1 before the JSON request is complete. Add it inside the callback function.

var recipient = 0;

$("#submit-button").click(function () {
    $.getJSON("/fetch.php?o=4&user=" + k, function (B) {
        $.each(B, function (index, result) {
            recipient = 1;
        });

        if (recipient == 1) {
            alert("yes");
        }
    });
});
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61