Saturday, July 24, 2010

jQuery Ajax Programming Trap

The following code looks logical if run in sequencial order but will fail in Ajax because its asynchronous nature:
$(document).ready(function(){
  $("input.myButton").click(function(event){
               var ret = handleAjaxCall($('#dataForm'));
               if(ret){              
                   alert('ajax call is successful');
               }else{
                   alert('ajax call failed');
               }
             $("#renewDetail").hide();                                     
               return false;
});}

function handleAjaxCall(form){
         var result = false; // default
         $.post("/myAction", form.serialize(), function(data){
             result = true; // ajax is successful
         });    
 
        return result;
}


You may think this code will work but it doesn't. The code will always prompt 'ajax call failed'.

The reason is that $.post() is asynchronous, so handleAjaxCall() will return before $.post() is completed.

Thus, the result value from handleAjaxCall is always false even though the $.post() is successful.

In order for Ajax to work, we need to handle all the successful logic inside $.post() callback function.
$(document).ready(function(){       
  $("input.myButton").click(function(event){
            $.post("/myAction", form.serialize(), function(data){
               alert('ajax is successful');
            });
});}

No comments :

Post a Comment