Skip to content Skip to sidebar Skip to footer

Ajax Post Gets Canceled By Redirect

I'm writing a small script to capture link clicks and save the link's URL into a database table in order to track how many times each link on a particular page is clicked. The link

Solution 1:

jQuery doesn't provide a callback for what you're looking for. Here are the available ready states:

Value   State   Description
0UNSENT  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.

You're looking for readystate 2, as that's the earliest you're aware of the fact that the server received the message.

This should get you off the ground:

var xhr = newXMLHttpRequest();
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 for further reading.

Solution 2:

Why do you post using Javascript when you are going to load a page any way?

Just update the db with the link clicked on the new page.

Perhaps using the referrer URL to track on what page the click was.

Or some other solution to get on what page the click was (e.g. url param) or some other way.

Solution 3:

When you leave a page, all pending requests are killed, and the new page loads. The 1st way is the correct way. Yes, there will be a delay when a link is clicked, that's because the POST request is running.

You can't run a request in the background of a page, if the user is not on that page.

Maybe you can save the link URL in a cookie, and put it into the DB when the next page loads.

Post a Comment for "Ajax Post Gets Canceled By Redirect"