Overview
GA4 event tracking captures user interactions beyond pageviews, including:
- Button clicks
- Form submissions
- File downloads
- Video plays
- Outbound link clicks
- Search queries
- Newsletter signups
Event Tracking Basics
GA4 Event Syntax
gtag('event', 'event_name', {
'parameter1': 'value1',
'parameter2': 'value2'
});
Recommended Events vs Custom Events
Recommended Events (predefined by Google):
loginsearchsharesign_upview_item_list
Custom Events (your own):
newsletter_signupwishlist_addproduct_comparisoncoupon_applied
Common OSCommerce Events
Search Event Tracking
Track when customers use the search function.
File: advanced_search.php or includes/header.php
<?php
// After search is performed
if (isset($_GET['keywords'])) {
$search_term = tep_output_string($_GET['keywords']);
?>
<script>
gtag('event', 'search', {
'search_term': '<?php echo addslashes($search_term); ?>'
});
</script>
<?php
}
?>
For header search box:
File: includes/header.php
<!-- Search form -->
<form name="quick_find" action="advanced_search_result.php" method="get">
<input type="text" name="keywords" id="header-search" />
<button type="submit"
</form>
<script>
function trackSearch() {
var searchTerm = document.getElementById('header-search').value;
if (searchTerm) {
gtag('event', 'search', {
'search_term': searchTerm
});
}
}
</script>
Newsletter Signup Tracking
File: newsletter.php or wherever newsletter form appears
<?php
// After successful newsletter subscription
if ($messageStack->size('newsletter') > 0 && strpos($messageStack->output('newsletter'), 'success') !== false) {
?>
<script>
gtag('event', 'sign_up', {
'method': 'Newsletter'
});
</script>
<?php
}
?>
For AJAX newsletter forms:
<script>
$('#newsletter-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'newsletter.php',
method: 'POST',
data: $(this).serialize(),
success: function(response) {
if (response.success) {
gtag('event', 'sign_up', {
'method': 'Newsletter'
});
alert('Subscribed successfully!');
}
}
});
});
</script>
Account Registration Tracking
File: create_account_success.php or create_account.php
<?php
// On successful account creation
if ($account_created) {
?>
<script>
gtag('event', 'sign_up', {
'method': 'Email',
'timestamp': '<?php echo time(); ?>'
});
</script>
<?php
}
?>
Login/Logout Tracking
File: login.php
<?php
// After successful login
if (tep_session_is_registered('customer_id')) {
?>
<script>
gtag('event', 'login', {
'method': 'Email'
});
</script>
<?php
}
?>
File: logoff.php
<script>
gtag('event', 'logout', {
'timestamp': '<?php echo time(); ?>'
});
</script>
Wishlist Events
File: wishlist.php or custom wishlist file
<?php
// When item added to wishlist
if (isset($_GET['action']) && $_GET['action'] == 'add_wishlist') {
$product_id = (int)$_GET['products_id'];
?>
<script>
gtag('event', 'add_to_wishlist', {
'items': [{
'item_id': '<?php echo $product_id; ?>',
'item_name': '<?php echo addslashes($product_name); ?>'
}]
});
</script>
<?php
}
?>
Product Review Submission
File: product_reviews_write.php
<?php
// After review submitted successfully
if ($review_submitted) {
$product_id = (int)$_GET['products_id'];
?>
<script>
gtag('event', 'review_submitted', {
'product_id': '<?php echo $product_id; ?>',
'rating': <?php echo (int)$_POST['rating']; ?>
});
</script>
<?php
}
?>
Contact Form Submission
File: contact_us.php
<?php
// After contact form successfully sent
if ($mail_sent) {
?>
<script>
gtag('event', 'contact_form_submit', {
'form_type': 'Contact Us',
'timestamp': '<?php echo time(); ?>'
});
</script>
<?php
}
?>
Coupon Code Applied
File: shopping_cart.php or checkout_payment.php
<?php
// When coupon successfully applied
if (isset($_SESSION['cc_id'])) {
$coupon_code = $_SESSION['cc_id'];
?>
<script>
gtag('event', 'coupon_applied', {
'coupon': '<?php echo addslashes($coupon_code); ?>',
'discount_amount': <?php echo $discount_amount; ?>
});
</script>
<?php
}
?>
File Download Tracking
Track PDF downloads (catalogs, manuals):
<a href="/downloads/catalog.pdf" 'PDF Catalog')">
Download Catalog
</a>
<script>
function trackDownload(filename, description) {
gtag('event', 'file_download', {
'file_name': filename,
'file_description': description,
'link_url': window.location.href
});
}
</script>
Outbound Link Tracking
Track clicks to external sites:
<script>
document.addEventListener('DOMContentLoaded', function() {
// Track all external links
document.querySelectorAll('a[href^="http"]').forEach(function(link) {
// Skip links to own domain
if (link.hostname !== window.location.hostname) {
link.addEventListener('click', function(e) {
gtag('event', 'click', {
'event_category': 'outbound',
'event_label': link.href,
'transport_type': 'beacon'
});
});
}
});
});
</script>
Social Share Tracking
File: product_info.php
<!-- Social sharing buttons -->
<a href="#" return false;">
Share on Facebook
</a>
<a href="#" return false;">
Share on Twitter
</a>
<script>
function shareProduct(network) {
gtag('event', 'share', {
'method': network,
'content_type': 'product',
'item_id': '<?php echo $product_id; ?>'
});
// Open share window
var url = '';
if (network === 'facebook') {
url = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(window.location.href);
} else if (network === 'twitter') {
url = 'https://twitter.com/intent/tweet?url=' + encodeURIComponent(window.location.href);
}
window.open(url, '_blank', 'width=600,height=400');
}
</script>
Video Play Tracking
If you have product videos:
<video id="product-video" src="/videos/product-demo.mp4" controls></video>
<script>
var video = document.getElementById('product-video');
video.addEventListener('play', function() {
gtag('event', 'video_start', {
'video_title': 'Product Demo',
'video_url': video.src
});
});
video.addEventListener('ended', function() {
gtag('event', 'video_complete', {
'video_title': 'Product Demo',
'video_url': video.src
});
});
</script>
Advanced Event Tracking
Scroll Depth Tracking
Track how far users scroll down pages:
File: includes/footer.php
<script>
(function() {
var scrollDepths = [25, 50, 75, 100];
var tracked = {};
function trackScrollDepth() {
var scrollPercent = Math.round((window.scrollY + window.innerHeight) / document.documentElement.scrollHeight * 100);
scrollDepths.forEach(function(depth) {
if (scrollPercent >= depth && !tracked[depth]) {
tracked[depth] = true;
gtag('event', 'scroll', {
'percent_scrolled': depth,
'page_path': window.location.pathname
});
}
});
}
var scrollTimeout;
window.addEventListener('scroll', function() {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(trackScrollDepth, 100);
});
})();
</script>
Time on Page Tracking
Track engaged time on product pages:
File: product_info.php
<script>
(function() {
var startTime = Date.now();
var engaged = false;
var engagementTime = 0;
// Track engagement (mouse movement, clicks, scrolls)
['mousemove', 'click', 'scroll', 'keypress'].forEach(function(event) {
document.addEventListener(event, function() {
engaged = true;
});
});
// Send engagement time every 30 seconds
setInterval(function() {
if (engaged) {
engagementTime += 30;
gtag('event', 'user_engagement', {
'engagement_time_msec': 30000,
'page_title': document.title
});
engaged = false;
}
}, 30000);
// Send final engagement on page unload
window.addEventListener('beforeunload', function() {
var totalTime = Math.round((Date.now() - startTime) / 1000);
gtag('event', 'time_on_page', {
'value': totalTime,
'page_path': window.location.pathname,
'transport_type': 'beacon'
});
});
})();
</script>
Form Abandonment Tracking
Track when users start but don't submit forms:
<script>
var formStarted = false;
var formSubmitted = false;
$('#contact-form input, #contact-form textarea').on('focus', function() {
if (!formStarted) {
formStarted = true;
gtag('event', 'form_start', {
'form_name': 'Contact Form'
});
}
});
$('#contact-form').on('submit', function() {
formSubmitted = true;
});
window.addEventListener('beforeunload', function() {
if (formStarted && !formSubmitted) {
gtag('event', 'form_abandon', {
'form_name': 'Contact Form',
'transport_type': 'beacon'
});
}
});
</script>
Error Tracking
Track JavaScript errors:
File: includes/header.php
<script>
window.addEventListener('error', function(e) {
gtag('event', 'exception', {
'description': e.message + ' @ ' + e.filename + ':' + e.lineno,
'fatal': false
});
});
</script>
Event Naming Best Practices
Use Consistent Naming
// GOOD - Consistent snake_case
gtag('event', 'add_to_cart', {...});
gtag('event', 'remove_from_cart', {...});
gtag('event', 'begin_checkout', {...});
// BAD - Mixed naming styles
gtag('event', 'addToCart', {...});
gtag('event', 'remove-from-cart', {...});
gtag('event', 'BeginCheckout', {...});
Use Descriptive Event Names
// GOOD - Clear and descriptive
gtag('event', 'newsletter_signup_footer', {...});
gtag('event', 'product_image_zoom', {...});
// BAD - Vague
gtag('event', 'click', {...});
gtag('event', 'action', {...});
Limit Custom Events
- Use recommended events when possible
- Create custom events only for unique interactions
- Don't track every single click
- Focus on business-critical events
Testing Event Tracking
1. Browser Console Method
// Open console (F12) and trigger event
// Watch console for confirmation
// Add debug logging
function trackEvent(eventName, params) {
console.log('Tracking:', eventName, params);
gtag('event', eventName, params);
}
2. GA4 DebugView
Google Analytics > Admin > DebugView
Enable debug mode:
gtag('config', 'G-XXXXXXXXXX', {
'debug_mode': true
});
3. Network Tab Monitoring
F12 > Network > Filter: collect
Trigger event and watch for network request to google-analytics.com/g/collect.
4. Browser Extensions
Install:
- Google Analytics Debugger - Shows GA hits in console
- GA4 Event Tracker - Visual event monitoring
Common Issues
Events Not Firing
Problem: Event code runs but nothing in GA4
Solutions:
- Check event name spelling
- Verify gtag is defined:
typeof gtag === 'function' - Check browser console for errors
- Ensure event fires after gtag.js loads
- Test in DebugView
Duplicate Events
Problem: Same event fires multiple times
Solutions:
// Use flags to prevent duplicates
var newsletterTracked = false;
function trackNewsletter() {
if (!newsletterTracked) {
newsletterTracked = true;
gtag('event', 'sign_up', {
'method': 'Newsletter'
});
}
}
Events Missing Parameters
Problem: Events fire but parameters are undefined
Solutions:
<?php
// Always validate before output
$product_name = isset($product_info['name']) ? addslashes($product_info['name']) : 'Unknown';
?>
<script>
gtag('event', 'view_item', {
'item_name': '<?php echo $product_name; ?>'
});
</script>
Event Reporting in GA4
View events in GA4:
Reports > Engagement > Events
Create custom reports:
Explore > Free Form
Add dimensions: Event name
Add metrics: Event count, Users