AJAX message canceled by redirect

I am writing a small script to capture links and save the link URL in the database table to track how many times each link is clicked on a specific page. Links to external sites.

So, I capture the click event in my JavaScript function, using jQuery to publish to a PHP page that stores data in MySQL, and then the JavaScript function redirects the user to the URL of the link they clicked on.

The problem I am facing is that it seems that the message never ends because there is a redirect. I worked on this, causing a redirect inside the callback, but this adds a few seconds to the delay because it is not called until the message is complete. I am looking for a way to simply send data and redirect the user immediately, regardless of whether the message succeeds or fails.

This is the current code with a workaround. It works fine, but adds a delay:

function trackClicks(event)
{
    var clicked = $(this).attr('href');

    $.post
    (
        $('#track-click-post-url').attr('value'),
        {
            action: 'track_landing_page_clicks',
            clicked_url: clicked,
            nonce: $('#track-click-nonce').attr('value')
        },
        function( response )
        {
            window.location = clicked;
        }
    );

    event.preventDefault(); 
}

And this is what I would like to do, but when I try, it never ends:

function trackClicks(event)
{
    var clicked = $(this).attr('href');

    $.post
    (
        $('#track-click-post-url').attr('value'),
        {
            action: 'track_landing_page_clicks',
            clicked_url: clicked,
            nonce: $('#track-click-nonce').attr('value')
        }
    );

    window.location = clicked;
    event.preventDefault(); 
}
+5
source share
3 answers

jQuery does not provide a callback for what you are looking for. Here are the available states of readiness:

Value   State   Description
0   UNSENT  open()has not been called yet.
1   OPENED  send()has not been called yet.
2   HEADERS_RECEIVED    send() has been called, and headers and status are available.
3   LOADING Downloading; responseText holds partial data.
4   DONE    The operation is complete.

readystate 2, , , .

:

var xhr = new XMLHttpRequest();
xhr.open("POST", clicked);
xhr.onreadystatechange = function() {
    if (xhr.readyState >= 2) window.location = clicked;
};
xhr.send($('#track-click-post-url').attr('value'));

https://developer.mozilla.org/en/XMLHttpRequest .

+7

, , . - . , , POST.

, .

, URL- cookie .

0

Javascript, ?

db , .

Perhaps using the referrer URL to keep track of which page was clicked.

Or some other solution to get to the page that was clicked (e.g. url param) or in some other way.

0
source

All Articles