Getting jQuery ajax and callbacks to Seaside into the right order


I guess having learned something new is what makes a day a good one. So I’ve had a good day today.

In my Seaside Application, I try to add a few fancy ajax gadgets that use Ajax and do something before and after the actual Ajax call is performed. Especially in the case where you need to do something only after the ajax call is finished, you need to always keep in mind that the Ajax call is asynchronous, that means if you do an $.ajax, the following javascript statements will be run after the ajax call is issued (in other words:  immediately), not after the call is finished.

I thought I knew all about this.

Until today.

Because I had something that looked like this:

$.ajax({
  "url": options.url,
  "data": [
    options.queryFields,
    options.serializeCallback+"="+self.val(),
  ].join("&"),
  "complete": drawTarget(),
});

Don’t worry about the data parameter, that’s not important for the moment. Just imagine I send out a Seaside Callback’s identification as part of the options to my plugin and that is what gets handed back to the server in this call.

The point of my post is about the complete callback.

It turns out that I had some strange effect in that the callbacks (the one from this ajax and one in the drawTarget() function) came into my Seaside image in the wrong order, but only after the ajax was done. So the complete callback worked to some extent, but not quite right.
It turns out the use of complete, success and so one as parameters to $.ajax has long been deprecated:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

So after I changed my ajax code to

$.ajax({
  "url": options.url,
  "data": [
    options.queryFields,
    options.serializeCallback+"="+self.val(),
  ].join("&"),
}).always(drawTarget());

The callbacks come in in the correct order and my application works as it should. This is just another proof of the “once you do it right, it simply works ” theorem, I guess😉

And, it also is another hint that reading documentation can sometimes be a good idea.