2

I need able or disable a click event depending on the server result. I have the following funcion using jquery:

$("#button").click(function(){
   var validated = true;
   $.ajax({
       url:  "/Foo",
       type: "POST",
       success:function(data){
           // alert(validated);  ----> true
           if(data){
               validated = false;
               // alert(validated);  ----> false
           }
       }
   });
   // alert(validated); ----> true
   return validated;
});

In the above code, always return true. I think the problem is that I set wrong the global variable validated. I have read this post and this but does not work for me. What am I doing wrong?

Community
  • 1
  • 1
Cristhian Boujon
  • 3,552
  • 10
  • 41
  • 81

1 Answers1

1

The problem is, that the AJAX call happens in a separate "thread" than the rest of the function. Thus, the thread with the click event runs on its own, does the AJAX call which is done ASYNCHRONOUSLY, and then returns. The AJAX thread never has the time to modify the validated var - the click handler has already returned.

The best way to solve this would be to make a callback from within the AJAX thread, or disable the element you want inside the AJAX thread itself, rather than returning a result to another function, which will then modify your button in another thread.

Filippos Karapetis
  • 4,197
  • 19
  • 36
  • Javascript doesn't have threads. The problem is that the AJAX success function happens after the handler function returns. – Barmar May 27 '13 at 22:50
  • This is why I put "threads" in quotes... Javascript doesn't have threads, but AJAX calls do behave LIKE threads - this makes the whole concept of asynchronous calls easier to explain – Filippos Karapetis May 27 '13 at 22:56