Call ajax in parallel instead of in a chain

We know ajax is an asynchronous call and doesn’t halts other ajax calls if calls are made same time.

Suppose I have a button and clicking on that button fires two ajax calls.

So when i click the button then both ajax get called same time and these calls don’t have any dependency to each other.

But there are situation where we need to do something else when both ajax call get completed like refreshing a section or showing success message.
For doing this we need know on which state all my ajax are completed. And its not necessary that ajax will be get completed in the same sequence I called.

$.post('page1.php',function(data1){});
$.post('page2.php',function(data2){});
$.post('page3.php',function(data3){});

Suppose i have these 3 ajax calls. Now i need to show an success message to user when all these are completed.
There are no way to do it if we make ajax calls in parallel.

So to make it simplified we made ajax call in chain means we call an ajax first and when that ajax completes then we call the 2nd ajax and so on.
When my last ajax call gets completed then we show the required message to the user because we are very sure that my ajax call gets fired because only when all my previous ajax are completed successfully.

Like

$.post('page1.php',function(data1){
    $.post('page2.php',function(data2){
        $.post('page3.php',function(data3){
            //Here we make sure all ajax call completed
        });
    });
});

Above code doesn’t has any problem at all, that code structure is very well trusted and never fails.

But don’t you think you are just wasting time because ajax will be call one by one and next subsequent call will fired only when previous one completed successfully.
Also ajax are ment to call asynchronously so you will able to call all 3 ajax parallel.

Now if you are able to detect the complete point of all 3 ajax calls then it will be big performace boosting.

We can do this by using jQuery deferred object.

We will use $.when() function, inside this function we will pass all ajax call and we will catch all ajax state using $.done() or $.then().

$.when(
    $.post('page1.php'),
    $.post('page2.php'),
    $.post('page3.php')
).done(function(data1, data2, data3){
    //here you will all 3 ajax calls response available when all
ajax call get completed.
});
$.when(   
    $.post('page1.php'),
    $.post('page2.php'),
    $.post('page3.php')
).then(function(data1, data2, data3){
    //here you will all 3 ajax calls response available when all
ajax call get completed.
});

If you want to call a specific success function if all gets completed successfully or call a failure function if one of the call failed then do it like.

$.when(
    $.post('page1.php'),
    $.post('page2.php'),
    $.post('page3.php')
).then(successCallBack, failureCallBack);

Why and how to abort an ajax call in jQuery.

Lets think about you have an input field and you attached an autocomplete function to that input field.

For an autocomplete functionality what we need to do is attaching a keyup event handler to that input field and every keyup call an ajax to get the desire results.

Lets think below is the input field
<input id=”search” name=”search” type=”text” >

And a div where we show the autocomplete list
<div id=”result”></div>

And the code for an autocomplete function is like

$(function(){
    $('#search').keyup(function() {
        var q = $(this).val();
        $.ajax({
            type: 'POST',
            data: 'q=' + q,
            url: 'AJAX_URL',
            success: function(response) {
                $('#result').html(response).show();
            }
        });
    });
});

Above code works great and you will have a nice autocomplete feature in place.

But did you think when you search by more than one character then what happen.

A new ajax request will be made for each and every character you entered. Lets take an example, you want to see an autocomplete list for “John”.

When you entered “J”, an ajax call will be made for “J”, then when you entered “o”, another call will be made for “Jo” and so on.

So to search “John”, you have 4 ajax calls for “J”, “Jo”, “Joh” and “John” and all 3 ajax response are useless to you except “John” one.

But you are thinking at the end of all ajax call user will get response of “John” and will see the correct response. And here you made the mistake. Remember ajax are asynchronous so it never happen sequentially.  You may call all ajax in a sequence but there are no guarantee that you will get the response in same sequential order.

Lets take the above example. You have 4 ajax calls in place. Though these are asynchronous calls, it may happen that you get response of ajax 4 before ajax 3 completes. So you were expecting results for “John” but you end up getting result of “Joh” which is weird to user.

Take another real life example. Suppose we are working on an e-commerce website where we list lots of product with different filter option.

Lets say we have selected t-shirts and in this page we have filter options for brands and all brands are associated with a checkbox to filter the list.

Here we made an ajax request when we click on a checkbox and filter the list.

Lets think i checked ‘Adidas’, ‘Nike’, ‘Reebok’ and ‘Puma’ and i will have 4 ajax call in place like

ajax 1: ‘Adidas’
ajax 2: ‘Adidas, Nike’
ajax 3: ‘Adidas, Nike, Reebok’
ajax 4: ‘Adidas, Nike, Reebok, Puma’

Though these are asynchronous call it may be possible you get ajax 1 response at the end. So what user will see? He will be seeing his all 4 filter options are checked but he is just seeing filter list by ‘Adidas’. Don’t you think, this is a very bad user experience?

So how we can solve this.

We will do one thing, before calling any ajax, we will check if there any pending ajax request for same ajax function. If there are any pending ajax call then we will cancel those and make a fresh/new ajax call.

jQuery provides a great function to cancel any ajax call any time called abort(). We will use this abort() function to cancel any pending ajax before calling the same.

We will take an variable which will store the status of any pending ajax call and default value will be set to null means no ajax call in place like

var progress = null;

This variable value will be updated when a ajax call is made like

progress = $.ajax();

We will set this variable value to null again when this ajax call completes like

complete: function(data) {
     progress = null;
 }

So progress has the latest ajax status. Before making any new ajax call we will check progress’s status and will see progress is null or not.

If progress isn’t null then we will abort the previous call then we will made the new call like.

beforeSend : function()    {
     if(progress != null) {
         progress.abort();
     }
 }

And the complete function will be like

$(function(){
    var progress = null;
    $('#search').keyup(function() {
        var q = $(this).val();
        progress = $.ajax({
            type: 'POST',
            data: 'q=' + q,
            url: 'AJAX_URL',
            beforeSend : function() {
                //checking progress status and aborting pending request if any
                if(progress != null) {
                    progress.abort();
                }
            },
            success: function(response) {
                $('#result').html(response).show();
            },
            complete: function(){
                // after ajax xomplets progress set to null
                progress = null;
            }
        });
    });
});

How to toggle an attribute in jQuery

In jQuery 1.9 version toggle() function deprecated. New toggle() helps you to hide and show elements with animation and easing effects.

Now if you need a function for toggling an attribute value on click event, how you will do it because jQuery doesn’t provides any function for this. For doing this you can write your own function and can use it in same way you use any other jQuery function.

$.fn.toggleAttr = function(attrName, attrVal1, attrVal2) {
return this.each(function() {
var self = $(this);
if (self.attr(attrName) == attrVal1)
self.attr(attrName, attrVal2);
else
self.attr(attrName, attrVal1);
});
};

Now this function will helps you toggle any attribute.

Lets see an example

Suppose i am having an image in page

<img src=”myUrl/test1.jpg” alt=”img1″ title=”img1″ id=”img”>

Now suppose i need to change image to test2.jpg when some click on test1.jpg and the reverse one. So we can do it using above function like

$(function() {
$(‘#img’).click(function(){
$(‘#img’).toggleAttr(‘src’, ‘myUrl/test1.jpg’, ‘myUrl/test2.jpg’);
$(‘#img’).toggleAttr(‘alt’, ‘img1’, ‘img2’);
$(‘#img’).toggleAttr(‘title’, ‘img1’, ‘img2’);
});
});

How to use HTML for jQuery dialog title

Latest version of jQuery UI doesn’t allow HTML as dialog title to avoid vulnerabilities. It only allows text. So if you want to show some icon or custom design for the title then you don’t have a way to do it from title property.

But we can do it by extending the dialog widget.

1st we will add an extra option to dialog property called titleIsHtml. We will set it as true if we want to use HTML for dialog title or false for text or even we can leave it so by default it will be text.

$(“#myDialog”).dialog({
        modal: true,
        title: “<div class=’widget-header widget-header-small’><h4 class=’smaller’><i class=’ic-file ‘></i> My Dialog</h4></div>”,
        titleIsHtml: true,
        autoOpen: false,
        width:800,
        height:’auto’
});

Now we are extending the dialog property like

$.widget(“ui.dialog”, $.extend({}, $.ui.dialog.prototype, {
        _title: function(title) {
            var $title = this.options.title || ‘&nbsp;’
            if( (“titleIsHtml” in this.options) && this.options.titleIsHtml == true )
                title.html($title);
            else title.text($title);
        }
}));

Here we are checking the titleIsHtml property of dialog, if it is set and true then we are setting dialog title using jQuery’s html() function which will allow to set HTML in dialog.

If titleIsHtml isn’t set or false then we are using jQuery’s text() function to set the title which will just put raw text as dialog title