Nirmal
Nirmal

Reputation: 9549

jQuery async:false and Firefox

When a user clicks on a link, I want to make an ajax call and wait for the call to complete before redirecting the user. Initially I used preventDefault() and window.location to achieve the result, but that prevented a user from doing Ctrl + Click (new tab).

So I ended up doing this, but for some reason the ajax call is never made in Firefox:

$('a.item-link').on('click', function(e){
    $.ajax({
        url: "http://123.456.789.012/c",
        type: 'GET',
        data: {
            'userId'   : '1234'
        },
        dataType: 'jsonp',
        async: false,
        cache: false,
        timeout: 1500
    });

    return true;
});

Any idea how could I do this synchronous call in Firefox?
Thanks for the help.

Upvotes: 0

Views: 2085

Answers (2)

Nirmal
Nirmal

Reputation: 9549

Thanks to @JeffB and @bobber205, I ended up doing this:

$('a.item-link').on('click', function(e){
    if(e.ctrlKey){
        var newTab = true;
    } else {
        e.preventDefault();
        var _this = this;
        var newTab = false;
    }

    $.ajax({
        url: "http://123.456.789.012/c",
        type: 'GET',
        data: {
            'userId'   : '1234'
        },
        dataType: 'jsonp',
        cache: false,
        timeout: 1500,
        success: function(){
            if(!newTab){
                window.location = $(_this).prop('href');
            }
        },
        error: function(){
            if(!newTab){
                window.location = $(_this).prop('href');
            }
        }
    });

    if(newTab){
        return true;
    }
});

I am just checking if ctrl key was pressed during the click and taking appropriate actions.

Thanks for the hint, experts. Sometimes, the simplest thoughts require reminder from others. Great community this is!

Upvotes: 1

bobber205
bobber205

Reputation: 13372

Make your element a button and don't do the redirection until the ajax call is done. Open in new window if ctrl button was down before the call was made.

Upvotes: 2

Related Questions