3

I am looking to add an event to successful submissions of a form in PHP (a purchased script). I found the function in PHP that triggers on success and I marked where I think the analytics goes...

function emailSuccessfullySent() {
global $translations, $lang, $options, $fdata, $is_ajax;

// redirect to custom "success" page if it's been set
if ( !empty($options['redirect_url'])) {
    if (!$is_ajax) {
        header('Location: '.$options['redirect_url']);
    } else {
        echo json_encode(array('redirect' => array($options['redirect_url'])));
    }
    exit;
}

// if no redirect has been set, echo out the success message
if ($is_ajax) {
    echo json_encode(array('success' => array($translations->form->success->title->$lang)));
    // analytics code here
} else {
    echo '<h2>'.$translations->form->success->title->$lang.'</h2>';
    // analytics code here
}

removeUploadsFromServer();
}

...however I am not sure how to fire the event JS:

ga('send', 'event', 'Form Button', 'submit', 'Feedback');
Ricardo Andres
  • 335
  • 3
  • 13

2 Answers2

5

You'll want to look into the Google Analytics server-side measurement protocol.

Here is a PHP implementation that I have success with, but it may be overkill for your use case (but at least it's a reference). Here is the full code, but I've simplified it for this post.

//Handle the parsing of the _ga cookie or setting it to a unique identifier
function ga_parse_cookie(){
    if ( isset($_COOKIE['_ga']) ){
        list($version, $domainDepth, $cid1, $cid2) = explode('.', $_COOKIE["_ga"], 4);
        $contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1 . '.' . $cid2);
        $cid = $contents['cid'];
    } else {
        $cid = ga_generate_UUID();
    }
    return $cid;
}

//Generate UUID v4 function (needed to generate a CID when one isn't available)
function ga_generate_UUID(){
    return sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), //32 bits for "time_low"
        mt_rand(0, 0xffff), //16 bits for "time_mid"
        mt_rand(0, 0x0fff) | 0x4000, //16 bits for "time_hi_and_version", Four most significant bits holds version number 4
        mt_rand(0, 0x3fff) | 0x8000, //16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low", Two most significant bits holds zero and one for variant DCE1.1
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) //48 bits for "node"
    );
}

//Send Data to Google Analytics
//https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#event
function ga_send_data($data){
    $getString = 'https://ssl.google-analytics.com/collect';
    $getString .= '?payload_data&';
    $getString .= http_build_query($data);
    $result = wp_remote_get($getString);
    return $result;
}

//Send Event Function for Server-Side Google Analytics
function ga_send_event($category=null, $action=null, $label=null, $value=null, $ni=1){
    //GA Parameter Guide: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters?hl=en
    //GA Hit Builder: https://ga-dev-tools.appspot.com/hit-builder/
    $data = array(
        'v' => 1,
        'tid' => 'UA-XXXXXX-Y', //***** Replace with your tracking ID!
        'cid' => ga_parse_cookie(),
        't' => 'event',
        'ec' => $category, //Category (Required)
        'ea' => $action, //Action (Required)
        'el' => $label, //Label
        'ev' => $value, //Value
        'ni' => $ni, //Non-Interaction
        'dh' => 'gearside.com', //Document Hostname
        'dp' => '/', //Document path
        'ua' => rawurlencode($_SERVER['HTTP_USER_AGENT']) //User Agent
    );
    ga_send_data($data);
}

Then, in the locations you commented, you'd simply place the function:

ga_send_event('Form Button', 'Submit', 'Feedback');
GreatBlakes
  • 3,971
  • 4
  • 20
  • 28
  • Your answer makes a lot of sense. I also had a co-worker glance at it since I'm not well versed in PHP, and he said it should work. For some reason, it isn't working. I'm going to mark this as the correct answer since it is exactly that. Sadly I may have to use a less accurate method if I can't figure it out soon. Thank you for your time. – Ricardo Andres Nov 24 '15 at 19:26
  • Without knowing a specific error you're running into, I'd just make sure that you've replaced the 'tid' value with your own GA tracking ID. You'll also want to update the hostname from gearside.com to your own hostname. In Google Analytics, check the Realtime event report, and I'd even test it on a static page (outside your form) with ```var_dump()``` to make sure it's all running properly. – GreatBlakes Nov 24 '15 at 22:13
  • 3
    A possible issue may be the line `$result = wp_remote_get($getString);` being WordPress specific. Using the code from this answer as an alternative appears to work: http://stackoverflow.com/questions/1239068/ping-site-and-return-result-in-php – Nick Mischler Dec 06 '16 at 20:58
0

Another option is to setup goal on your "success" page.

After successful form submission user will be redirected to success page and trigger goal in Google Analytics.

Alex
  • 639
  • 1
  • 5
  • 7
  • This is a good plan B, but at the moment the form submission does not redirect to another page. I am trying to avoid this option for now. – Ricardo Andres Nov 24 '15 at 19:29