Reputation: 7663
What is the best way of executing google tracking javascript when an ajax request has successfully completed?
The ajax request:
$('#form').ajaxSubmit({
url:'process.php',
success:function(response) {
if(response == 'success')
{
// trigger analytics code
}
}
});
Google Adwords Code:
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = xxxxxxx;
/* ]]> */
</script>
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/"/>
</div>
</noscript>
Would I need to add the analytics code to a separate js file and then use http://api.jquery.com/jQuery.getScript/ ?
Or could I just append <img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/"/>
to the page in the success callback?
Upvotes: 1
Views: 4410
Reputation: 7663
In the end the following I found just appending the img to be the simplest solution:
$('#form').ajaxSubmit({
url:'process.php',
success:function(response) {
if(response == 'success')
{
// trigger adwords code
$('#holder').append('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/"/>');
}
}
});
Upvotes: 2
Reputation: 2936
There are a few ways you could do this. Probably the most simple way would be to include all the Google Analytics code within its own div, then use the successful condition of your AJAX request to load the image and script sources. Here's an example:
<div id="GAcode">
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = xxxxxxx;
/* ]]> */
</script>
<script id="conversionScript" type="text/javascript" src="">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src=""/>
</div>
</div>
<script type="text/javascript">
$('#form').ajaxSubmit({
url:'process.php',
success:function(response) {
if(response == 'success')
{
$("#conversionScript").src("http://www.googleadservices.com/pagead/conversion.js");
$("#GACode img").src("http://www.googleadservices.com/");
}
}
});
</script>
Doing this would ensure that none of the Google specific code would be recognized until your AJAX request returned a successful response.
Edited to remove the source of the image. Forgot to do that, sorry.
Upvotes: 1