Using JavaScript to extract field data from Gravity Forms for external tracking

I’m trying to integrate our form data with an analytics platform that gave us this JavaScript snippet to collect user information:

<script type="text/javascript">
   var _tracking_data = {
      "user_first": "FIRST_NAME_VALUE",
      "user_last": "LAST_NAME_VALUE",
      "user_email": "EMAIL_VALUE"
    };
    _tracking_send('submit', 29841, null, JSON.stringify(_tracking_data));
</script>

I added this code using the gform_confirmation hook in my theme’s functions.php file. The idea is to trigger this script when someone submits the form:

add_filter( 'gform_confirmation_52', 'add_tracking_script', 10, 4 );
function add_tracking_script( $confirmation, $form, $entry) {
        $first_name = rgar( $entry, '2.1' );
        $confirmation .= "<script type='text/javascript'>
   var _tracking_data = {
      'user_first': $first_name
    };
    _tracking_send('submit', YYYYYY, null, JSON.stringify(_tracking_data));
</script>";
 
    return $confirmation;
}

The problem is that no data seems to reach the tracking system. Could there be an issue with how I’m implementing this code?

Had the same nightmare a few months ago. The redirect was firing too fast - didn’t give the tracking script time to execute. Analytics platforms need a moment to process and send data, but form confirmations redirect instantly. I switched to the gform_after_submission hook. It runs server-side after processing but before redirecting. Then use wp_add_inline_script to inject your tracking code properly. Also check if your analytics platform does server-side tracking - way more reliable than client-side JavaScript that gets blocked or fails to load.

u’re missing quotes around the PHP var in your JS. Wrap $first_name with quotes like '$first_name' or it won’t be valid JSON. also, check your browser console for errrors - that’s where these issues usually show up.

It’s probably a timing issue. The tracking script fires right after form submission, but analytics platforms usually need a second to initialize. I’ve hit this before - the tracking system just isn’t ready for the data yet. Try wrapping your tracking call in setTimeout() with about 500ms delay. Also, don’t embed PHP variables directly in JavaScript - use wp_json_encode() to escape them properly. One more thing: check if your analytics platform needs the page to stay loaded for a bit to actually send the data.