-1

Stuck in Jquery with I think something quite simple but I don't understand why it does not work.

I have a $.post that retrieves a value from an asp file and puts it into a variable in my main page.

var bankmsgstatus;
$.post("bankmsgstatus.asp", {}, function(data3) {
    bankmsgstatus = data3;

});

However, when I try to do a if comparison, it does not work.

if (bankmsgstatus == 'on') {
    alert("Value: " + bankmsgstatus);
} else {
    alert("Value: " + bankmsgstatus);
}

All I get is that the bankmsgstatus value is 'undefined'

What am I doing wrong?

Thanks

Saj
  • 297
  • 3
  • 6
  • 23
  • Where is this `if` located? I suspect you should read through this: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – James Montagne Feb 10 '14 at 02:08
  • Thanks James for the reference. That is a very good article! – Saj Feb 10 '14 at 05:00

1 Answers1

1

I would guess that the issue is caused by the fact that $.post() is asynchronous. It does not complete right away so the variable bankmsgstatus is not yet set when you're trying to use it.

I would suggest this:

$.post("bankmsgstatus.asp", {}, function(data3) {
    var bankmsgstatus = data3;

    if (bankmsgstatus == 'on') {
        alert("Value: " + bankmsgstatus);
    } else {
        alert("Value: " + bankmsgstatus);
    }
});

Asynchronous programming in javascript requires that any data produced by the success or completion handler for the asynchronous operation can only be used from that completion handler function either in the function itself or passed as an argument to some function that you call from there. That's because the timing of when this completion function gets called is unknown (some time in the future) and your other javascript continues to run and does not wait for it to complete. Thus, the only way you know for sure when it's done is by trigger your operation that uses the result FROM the actual completion handler itself.

jfriend00
  • 683,504
  • 96
  • 985
  • 979