Asa Carter
Asa Carter

Reputation: 2225

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?

Upvotes: 0

Views: 929

Answers (1)

JCOC611
JCOC611

Reputation: 19709

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

Upvotes: 1

Related Questions