Search code examples
javascriptjqueryfacebookfacebook-javascript-sdkgravityforms

How can I use a function parameter to define a customEvent in facebook conversion API


I want to record in Facebook event manager which questions a user exits. Gravity Forms provides the function below; it runs your code block when a user moves to the next question on the form.

jQuery(document).on('gform_page_loaded', function (event, form_id, current_page) {
// my code here
});

Facebook recommends to use the following snippet to record a custom event in event manager.

fbq('trackCustom', 'ShareDiscount', {promotion: 'share_discount_10%'});
// ShareDiscount is the custom event name

I need the event name defined using the current_page parameter value from the Gravity Forms function. When I console.log(current_page), I see the expected value in the console. However, Facebook doesn't recognize the event when I try to use the parameter in the Facebook fbq code. Example:

// NOT WORKING - facebook doesn't record the event
jQuery(document).on(
  'gform_page_loaded',
  function (event, form_id, current_page) {
    console.log(current_page); // console logs current_page as expected
    return fbq('trackCustom', `${current_page}`, {
      futureUse: 'to_be_defined_later',
    });
  }
);

When I use just a static string, Facebook records the event as expected. But I need the current page value to be used allowing event names to be defined dynamically using the current_page parameter.

// WORKING - facebook records the static string as an event
jQuery(document).on(
  'gform_page_loaded',
  function (event, form_id, current_page) {
    return fbq('trackCustom', 'Static Event Name', {
      futureUse: 'to_be_defined_later',
    });
  }
);

I have tried the current_page.toString() method without luck. Without duplicating code in a many if statements, how can one dynamically define the custom event name?


Solution

  • According to the documentation for custom event names:

    Custom event names must be strings, and cannot exceed 50 characters in length.

    Well, since you've tried converting it to string, I'd say it also has a minimum character length (that should be greater than one or two)...Try something like this:

      function (event, form_id, current_page) {
        return fbq('trackCustom', 'MyEventName-' + current_page, {
          futureUse: 'to_be_defined_later',
        });
      }