Sitecore trigger analytics goal from Jquery using ASMX web service

This article demonstrates a way of asynchronously triggering a Sitecore Analytics goal using Jquery Ajax and ASMX web services. This also demonstrates PostMan, a chrome REST client, that makes AJAX development much easier.

To start with the following code needs to be added to the user control (.ascx part) and this need to be added to a page. In Sitecore world this involves associating this with a sub-layout and adding it to a page:

<script type="text/javascript"> 
    $(document).ready(function () {
      $("#buttonGoal").click(function() {

     $.ajax({
      url: "/custom/customgoal.asmx/TriggerBookingGoal",
      data: "{goal:'Received call-back', url:'" + document.URL + "'}",
      dataType: 'json',
      contentType: "application/json; charset=utf-8",
      type: "POST",
      success: function (data) {
        console.debug('ajax goal added successfully');
        $("#buttonGoal").after("<br/>" + data.d);
         }
     });
    });
 });
</script>

<div id="buttonGoal" style="background-color:aqua; padding: 20px;">
   Hit Your Goal
</div>

Note: Content-Type must be specified in the JQuery Ajax call!

Next step is to add a web service in Visual studio and make sure the [System.Web.Script.Services.ScriptService] attribute is in place, as it is commented out by default.

createe-web-service-visual-studio

The code that I have used for the server side .Net web service is below. Note the attributes on the webmethod and the scriptmethod.

/// <summary>
/// Summary description for CustomGoal
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class CustomGoal : System.Web.Services.WebService
{
  [WebMethod(EnableSession = true)]
  [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
  public string TriggerBookingGoal(string goal, string url)
  {
  if (!Sitecore.Analytics.Tracker.IsActive)
  {
    Sitecore.Analytics.Tracker.StartTracking();
  }

  if (!Sitecore.Analytics.Tracker.IsActive || Sitecore.Analytics.Tracker.CurrentPage == null)
  {
    return "Sitecore Analytics Pipline not invoked or manually initialised";
  }

  Item goalItem = GetGoal(goal);
  if (goalItem == null)
  {
    return "no tracking item found";
  }

  PageEventItem currentgoal = new PageEventItem(goalItem);
  VisitorDataSet.PageEventsRow pageEventsRow = Sitecore.Analytics.Tracker.CurrentPage.Register(currentgoal);
  pageEventsRow.Data = "url clicked: " + url;
  Sitecore.Analytics.Tracker.Submit();
  return "added goal (" + goal + ") successfully for url " + url;
}

private Item GetGoal(string goal)
{
  const string DefaultGoal = "Received call-back";
  const string DefaultGoalLocation = "/sitecore/system/Marketing Center/Goals/Action goals/";

  Item goalItem = Sitecore.Context.Database.GetItem(DefaultGoalLocation + goal);

  if (goalItem == null)
  {
    goalItem = Sitecore.Context.Database.GetItem(DefaultGoalLocation + DefaultGoal);
  }
  return goalItem;
  }
}

So now it’s time to hit the button (div in this case) and debug it.

button-asmx-button

debug-asmx-jquery-post-example

If you get stuck, and this applies to all Rest web development, then you can use postman a Chrome plugin. See here
postman-asmx-jquery-post-example

Make sure you add the headers: content-type: application/json

That’s it.
It you want to check the pageevents have been added then you may want to check them using the following SQL on your analytics DB:

SELECT top(20) *
   FROM [PageEvents]
   order by DateTime desc

Additional notes:

This example required the request be processed by the Sitecore Analytics pipeline and therefore it is important that the ASMX file is not included in the urls that Sitecore ignores (ie don’t include it in the¬†<setting name=”IgnoreUrlPrefixes” ¬†values)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>