0

I have a button on a page (id = "searchButton"), that, when clicked submits a form (post). Before the post occurs, I want to log some information to Google Analytics. So I have the following JS code to do this:

$(document).ready(function () {
    // Log some information to GA
    $('#searchButton').click(function (e) {
        LogSearch();
        LogDestinations();
        LogTourTypes();
        LogIndependent();
    });
});

I'm wondering if I'm doing this correctly? Specifically, I'm curious whether the actual post is occurring before all four function calls are made. Or will all four function calls complete before the form actually posts, consistently, across all browsers? I want the form to post, but I also want these four JS functions to execute first.

In case it helps, I'm calling Google Analytics using their standard method of sending events:

ga('send', 'event', "Accommodation Search", "Accommodation Search Counter", "", 0);

And the HTML where the button is defined:

    <div class="col-xs-12">
        <input type="submit" value="Search" class="btn btn-primary" id="searchButton" />
    </div>
Randy Minder
  • 47,200
  • 49
  • 204
  • 358

1 Answers1

2

Normally they "might not" succeed, because the page is starting to unload.

If you're targeting modern brosers, you can use the transport: beacon flag that's designed to overcome this particular issue:

ga('send', 'event', 'click', 'download-me', {transport: 'beacon'});

This however won't work on older browsers or with IE.

If you want to target those browsers, it's common to just delay the redirect for a small amount of time in hope that the requests make it in that time:

$(document).ready(function () {
    $('#searchButton').click(function (e) {
        // Prevent the link from working normally
        e.preventDefault();

        // Log some information to GA
        LogSearch();
        LogDestinations();
        LogTourTypes();
        LogIndependent();

        // Fire up the link after 500 milliseconds
        var href = $(this).attr("href");
        setTimeout(function() {
            document.location.href = href;
        }, 500);
    });
});

If you really want to make sure that all the events are sent, you can use the analytics event callback, wrap it to promises and fire up the link like above. That should look something like this:

$(document).ready(function () {
    $('#searchButton').click(function (e) {
        // Prevent the link from working normally
        e.preventDefault();

        // Log some information to GA, return a promise
        var allEventsSentPromise = SendAllEvents();

        // Fire up the link after promise has resolved
        var href = $(this).attr("href");
        allEventsSentPromise.then(function() {
            document.location.href = href;
        });
    });
});

...but that would require that you look into promises.

jehna1
  • 3,110
  • 1
  • 19
  • 29