-1

We are building our tracking tool, and we want to keep track of the CTA's on our website.

Here is the code for that:

<script type="text/javascript">
   var $ = jQuery;         
   $("a").click(function () {
            var link = $(this);
            var href = link.attr('href');
            var noProtocol = href.replace(/http[s]?:\/\//, '');
            $.ajax({
                type: 'GET',
                url: 'https://ipinfo.io/json?token=369f3980fa1a62',
                success: function (response) {
                    $.ajax({
                        type: 'POST',
                        url: 'https://myserver.com/api/events',
                        headers: {},
                        crossDomain: true,
                        data: JSON.stringify({
                            'distinct_id': '',
                            'name': 'button_clicked',
                            'page': noProtocol,
                            'domain': document.domain,
                            'referrer': document.referrer,
                            'ip_address': response.ip,
                            'region': response.region,
                            'postal': response.postal,
                            'location': response.loc,
                            'country': response.country,
                            'city': response.city

                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {
                            //do nothing
                            console.log(msg);
                        }
                    });
                }
            });
        });

</script>

When someone clicks the link, it starts to post to our server but because tag redirects the page, the request is canceled. How to avoid this request is being canceled?

Burak
  • 5,706
  • 20
  • 70
  • 110

1 Answers1

1

One thing you can do is hijack all the links and rewrite them in such a way that It will have to call a function which does the redirection eventually.

<a href="/dashboard">Dashboard</a>

Becomes something like

<a href="#" data-href="/dashboard">Dashboard</a>

Add a script after all your HTML elements just before </body>

(function() {
    // Do your element manipulation here
})();

Then you can create an onClick event for all a tags with data-href where you can track and then eventually redirect.

var elements = document.querySelectorAll(a[data-href]);

elements.forEach(function(elemement) {
    elemement.addEventListener("click", function(e) {
        // Do something cool here
    });
});