Search code examples
jqueryajaxjquery-post

jQuery submit ajax post on anchor click


When an anchor is clicked I send a POST request to a server cross browser to track a click. However the next page loads before the request receives a response and the request is aborted.

$('body').on('click', '.link a', function() {
    $.post('https://someserver.com/', {
        param: 'here'
    });
});

How can ensure the request receives a response before the page loads?


Solution

  • Prevent the default action until you hear a response:

    $('body').on('click', '.link a', function(e) {
        e.preventDefault();
        var href = $(this).attr("href");
        $.post('https://someserver.com/', {
            param: 'here',
            success: function(){
                window.location.href = href;
            }
        });
    });