jQuery submit ajax post on anchor click

930 Views Asked by At

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?

1

There are 1 best solutions below

3
JCOC611 On BEST ANSWER

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;
        }
    });
});