March 25

jQuery promises

Sometimes it is required to execute callback right after the last of related Ajax call is completed. In this example there are 6 div elements (result1, result2, result3, result4, result5 and totals). There is external PHP script (call.php) which returns random number. Result DIV elements are populated asynchronously. Totals DIV element should contain sum of result DIV elements.

Ajax request is sent 5 times but it is unknown which request will be at the end. So it is questionable where to put code for calculating totals. Although setTimeout or global Ajax events can be utilized we should avoid them because of unpredictable results.

Fortunately, there is a JavaScript Promises functionality. jQuery has its own implementation which is well integrated with Ajax event handlers.

Callback function inside done() event will always execute right after last Ajax call.

February 9

jQuery data attribute

I believe that most of you are familiar with jQuery data() function. A lot of things can be done in convenient way using this functionality. I will show you one example. Let’s assume that you are creating news list widget. Content of this widget is based on category id. So there are two elements, category links and news list box.
Each of category link has jQuery click handler attached to itself. Click event triggers news box refresh.
Let’s examine code behind this:

Each link has refresh-news class so that single event can be attached. Category id is stored using data-catid attribute. jQuery has its own mechanism for parsing data attribute so it is enough to call $(this).data(‘catid’) inside event handler.