Reputation: 25369
I have a js widget which is embedded in random sites.
When a user clicks a link I want to report it to my server.
To call my server I create a tag dynamically with src containing the parames reported to the server.
If I do it on onclick event and return true from the onclick, the server probably will not get the call because the browser changes the page (is this correct?).
If I do it on onclick and return false then use redirect after the call to the server is returned, I lose the back button functionality because browsers like IE do not support the back button after redirect.
Any idea of how to do this in a robust way?
Upvotes: 0
Views: 1768
Reputation: 27342
There is no problem. If you add an onclick handler to the <a>
elements that sends an AJAX POST to the server (registering the click), this will arrive at the server, the page will still move on to the clicked link, and the back button will work as expected.
Example in jQuery:
$('a').live('click', function () {
$.post('/registerclick/', { data: $(this).attr('src') }, function () {});
});
The reason this works, is because the client/server model in HTML specifies that when a request is sent to the server, it cannot be cancelled. Therefore the following applies:
href
attributeThe browser isn't aware of the 3rd step; but that doesn't matter for the server.
Upvotes: 4