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

2 Answers 2

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

Comments

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

1 Comment

is there a way to make sure JSON request is complete, so i don't have to have it in the callback function?

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.