We recently ran into an issue with tracking Google Website Optimizer Conversions when using a form that submits using AJAX with no page refresh. Typically you place Google Website Optimizer’s conversion code on your “Thank you” page but we needed a solution that worked when using AJAX.
We found the solution and we hope it provides you some help to!
The Issue – Tracking conversions using AJAX and no conversion page
If you have used Google Website Optimizer you are aware that you need a page that is the “Control Page” then you need a “Conversion Page”. Now we were doing Landing Page Optimization and we were testing out headlines on a lead form. However we processed the form with AJAX so upon successful submission the user was simply presented with a thank you message rather than being directed to a thank you page.
We were using AJAX to submit the form using the following process:
- Javascript validates form upon submission
- Posts to PHP file
- PHP file returns if message was sent or not
- If successful, display thank you message
Note: our process is more in depth but this is an overview.
Now this all happens with the user never leaving the page, never going to a stand-alone “Conversion Page” so we were left without the ability to track conversions for our test.
Typical GWO (Google Website Optimizer) Conversion Code
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['gwo._setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['gwo._trackPageview', '/XXXXXXXXXX/goal']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
Replace the X’s with the information from your tracking code.
The Solution
Now, we can make 2 calls from the javascript file to make this all work. In our script.js file we check the response from the php file, if it was successful we display the thank you message. Now you can also add the Conversion code as follows:
_gaq.push(['gwo._setAccount', 'UA-XXXXXXXX-X']); _gaq.push(['gwo._trackPageview', '/XXXXXXXXXX/goal']);
Replace the X’s with the information from your tracking code.
Adding those 2 lines from the Conversion code is all that is needed. If you review the rest of the code, you will notice it is all included in the standard Google Analytics Tracking Code so you do not need to repeat it.
Once you add that to your javascript, upon successful submission it triggers the “__gaq.push” javascript and tracks the Goals in Google Website Optimizer. Tried, Tested and True!
