Monday, November 15, 2010

jQuery complete callback not called

OK my billions of followers, here is another one. Recently at work we had a case where the complete callback in jQuery's ajax class did not get invoked. The success method got called, but the complete method never did.
Our ajax calls go through two JavaScript objects before they make the actual jQuery $.ajax call, so the problem had something to do with that as well, but to oversimplify it,  if there is a JavaScript error during the execution of the success callback, the complete callback will NOT get invoked. Here is the source:



<html>
   <head>
      <title> jQuery test</title>
      <script src="jquery-1.4.3.min.js"></script>
      <script type="text/javascript">
         function testClick() {
          $.ajax(
            {
            url: "somePage.html",
            success: function(data){
               console.log('success called');
               $('#targetDiv').html(data);
               var someObject;
               //if you comment out the following line out, complete will get called
               someObject.nonExistingProperty = "blah";
              },
            complete : function() {
               console.log('complete called');
              }
            });
          }
      </script>
   </head>
   <body>
      <h1> <span style="color:green">jQuery  Ajax Complete test</span> </h1>
      <input id="testButton" type="submit" value="click me to test" onclick="testClick()" />
      <div id="targetDiv" style="margin-top:10px">
      </div>
   </body>
</html>

4 comments:

  1. Oh god thank you very much! I've lost two hours trying to figure it out, and at last it was so simple!

    ReplyDelete
  2. @Boyko: same thing. how stupid I am. I just did not look at the console and was trying to debug complete event. Thanks a million times!!!

    ReplyDelete
    Replies
    1. Thanks for leaving a note my friend! Our job often makes us feel stupid, but at the end of the day, it's a whole bunch of fun :). Thanks for the nice note again!

      Delete