Capture form submission buried in ajax/javascript and no easy event handler

When trying to capture a successful form submission or user action, sometimes they are buried deep within Javascript libraries, or on page widgets, with no good way to reliably tie into their events.  These are cases where the typical onclick may not be a good enough proxy if you can’t capture failures, errors, or the difference between one button on the next due to the way that widget may have been created.

Fortunately, many sites are using jQuery to do a lot of this heavy lifting, and if the result of this user action is an ajax request – we can easily tap into these using jQuery’s “ajaxSuccess” event

$(document).ajaxSuccess(function(event, xhr, settings) {
  if ( settings.url == "ajax/test.html" ) {
    $( ".log" ).text( "Triggered ajaxSuccess handler. The ajax response was: " +
                      xhr.responseText );
  }
});

This event runs each time jQuery handles a successful ajax call, from anywhere within the application (page).  Instead of daisy-chaining a bunch of event handlers and scraping for errors, or waiting for new content to determine success – we can just monitor the behind-the-scences data exchanges.  The third callback parameter “settings” has most of the relevant information right at your fingertips.

$(document).ajaxSuccess(function(event, xhr, settings){
    if(settings.type=="POST"){
        //do something for successful POST requests
        if(settings.url == '/post/like'){
            // maybe a request to an API to "like" a "post"
            _gaq.push(['_trackEvent','Social','Like']);
        }
    }else{
        //do something for successful GET requests
        if(settings.url == '/locations'){
            // maybe a load of a locations widget, returning stores nearest you
            _gaq.push(['_trackPageview','StoreLocator']);
        }
    }

});

Makes implementing analytics in this case pretty slick, and allows you to handle it all within one little event dispatcher function, as it determines what event to send based on the successful ajax reqeusts.

Leave a Reply

Your email address will not be published.