54

I'm pretty new to javascript, and therein probably lies my problem. I'm trying to track AdWords conversions that occur within a widget on our site. The user fills in a form and the result from the widget is published in the same div without a page refresh. The issue I'm having is when I try to appendChild (or append in jQuery) both script elements in Google's code (shown below) the page gets 302 redirected to a blank Google page (or at least that's what it looks like through FireBug). I'm able to provide a callback method for the results of the form, and that's where I'm trying to insert the AdWords tracking code. For reference, this is the code provided by Google:

<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 993834405;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "bSpUCOP9iAIQpevy2QM";
/* ]]> */
</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/pagead/conversion/993834405/?label=bSpUCOP9iAIQpevy2QM&amp;guid=ON&amp;script=0"/>
</div>
</noscript>

Pretty standard stuff. So, what I'm trying to do is insert this into the results page using the callback method (which is provided). Frankly, I'm redirected no matter when I try to insert this code using js or jQuery (either on original page load or in the callback) so maybe the callback bit is irrelevant, but it's why I'm not just pasting it into the page's code.

I've tried a number of different ways to do this, but here's what I currently have (excuse the sloppiness. Just trying to hack my way through this at the moment!):

function matchResultsCallback(data){

    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.text = scriptTag.text + "/* <![CDATA[ */\n";
    scriptTag.text = scriptTag.text + "var google_conversion_id \= 993834405\;\n";  
    scriptTag.text = scriptTag.text + "var google_conversion_language \= \"en\"\;\n";   
    scriptTag.text = scriptTag.text + "var google_conversion_format \= \"3\"\;\n";
    scriptTag.text = scriptTag.text + "var google_conversion_color \= \"ffffff\"\;\n";
    scriptTag.text = scriptTag.text + "var google_conversion_label \= \"bSpUCOP9iAIQpevy2QM\"\;\n";
    scriptTag.text = scriptTag.text + "/* ]]> */\n";
    $('body').append(scriptTag);

    $('body').append("<script type\=\"text\/javascript\" src\=\"http://www.googleadservices.com/pagead/conversion.js\" />");
    //I have also tried this bit above using the same method as 'scriptTag' with no luck, this is just the most recent iteration.

    var scriptTag2 = document.createElement('noscript');
    var imgTag = document.createElement('img');
    imgTag.height = 1;
    imgTag.width = 1;
    imgTag.border = 0;
    imgTag.src = "http://www.googleadservices.com/pagead/conversion/993834405/?label=bSpUCOP9iAIQpevy2QM&amp;guid=ON&amp;script=0";

    $('body').append(scriptTag2);
    $('noscript').append(imgTag);
}

The really odd thing is that when I only insert one of the script tags (it doesn't matter which one), it doesn't redirect. It only redirects when I try to insert both of them.

I've also tried putting the first script tag into the original page code (as it's not making any calls anywhere, it's just setting variables) and just inserting the conversions.js file and it still does the redirect.

If it's relevant I'm using Firefox 3.6.13, and have tried the included code with both jQuery 1.3 and 1.5 (after realizing we were using v1.3).

I know I'm missing something! Any suggestions?

Kevin Pope
  • 2,964
  • 5
  • 32
  • 47
  • 2
    For the time being I've (presumably) gotten this working by just dumping the adwords code into an iframe and loading the iframe when the callback occurs. I'm sure there's a more elegant way, though. – Kevin Pope Feb 23 '11 at 04:46
  • 75
    cant get over `document.createElement('noscript');`. lolz – Andrew Bullock Feb 16 '12 at 21:17
  • Note that the `$(...).html(...)` function will execute JavaScripts but the main problem as far as I can tell is that the global variables are defined with the "var" keyword. I'm not sure that the append() function would also run the scripts properly. Anyway, it is a better idea to use the code in Microscopic answer (but without the 'var' keywords.) – Alexis Wilke Jul 22 '12 at 01:15
  • Hi Alexis, I setup a test page with `var foo = 1234;` declared in its own `script` in the head of the page. Then, with some Ajax i called upon `jQuery('#myDiv').html('');` and found that yes, it was able to access the value of `foo`, so i'm not entirely sure this is the problem. (Yes, myTestScript.js was even on a different domain) – Funka Jul 23 '12 at 23:51
  • Some follow-up to my previous comment above : As stated, the test I ran did have access to my variables and found I was able to `alert` them just fine, etc., but interestingly, my attempts at using `document.write` did _not_ work and (see my _other_ comment elsewhere on this page) is why I suspect this doesn't work as we would hope... Using an iframe is a suggestion i've seen a few other places, so I might try that later, but for now we're going to try just using the 1x1 hidden pixel that you normally see in the `noscript` block, and see if that is "good enough" for the client... – Funka Jul 24 '12 at 01:36
  • jQuery + Ajax : http://stackoverflow.com/questions/27149647/how-to-implement-a-google-adwords-conversion-pixel-using-ajax-on-a-submit-butt/27149886?noredirect=1#comment42795611_27149886 – Imnotapotato Nov 26 '14 at 15:02

12 Answers12

52

Nowadays it is convenient to use the Asynchronous Tag at http://www.googleadservices.com/pagead/conversion_async.js that exposes the window.google_trackConversion function.

This function can be used at any time. For example after submitting a form, like in your case.

See https://developers.google.com/adwords-remarketing-tag/asynchronous/


Update 2018

Situation changed and it seems that you have more options now with the gtag.js: https://developers.google.com/adwords-remarketing-tag/

LeZuse
  • 1,132
  • 10
  • 17
39

If you're using jQuery in your pages, why don't you use the getScript method of the same to poll the conversion tracking script after setting the required variables?

This is what I usually do, once I've received a success response from my AJAX calls.

var google_conversion_id = <Your ID Here>;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "<Your Label here>";
var google_conversion_value = 0;
if (100) {
    google_conversion_value = <Your value here if any>;
}
$jQ.getScript( "http://www.googleadservices.com/pagead/conversion.js" );

This works just fine for me. If you want a more detailed example:

$.ajax({
    async:      true,
    type:       "POST",
    dataType:   "json",
    url:        <Your URL>,
    data:       _data,
    success:    function( json ) {

            // Do something
            // ...

            // Track conversion
            var google_conversion_id = <Your ID Here>;
            var google_conversion_language = "en";
            var google_conversion_format = "3";
            var google_conversion_color = "ffffff";
            var google_conversion_label = "<Your Label here>";
            var google_conversion_value = 0;
            if (100) {
                google_conversion_value = <Your value here if any>;
            }
            $.getScript( "http://www.googleadservices.com/pagead/conversion.js" );

        } // success
});

If you use other libraries such as Mootools or Prototype, I'm sure they have similar in-built methods. This AFAIK is one of the cleanest approaches.

halfer
  • 19,824
  • 17
  • 99
  • 186
miCRoSCoPiC_eaRthLinG
  • 2,910
  • 4
  • 40
  • 56
  • Hey thanks for this. I did end up doing this essentially this way, with the getScript jQuery call. Forgot to update it once I actually solved it, though. :-) – Kevin Pope May 12 '11 at 01:52
  • No, it doesn't, it's up to you. – El Yobo Nov 14 '11 at 10:03
  • 6
    Don't you need to change "var google_conversion_id" and other variables to be global? Like "window.google_conversion_id = x"? – Evgeny Mar 15 '12 at 13:52
  • 5
    Testing this solution, it didn't really work for us. the google conversion JS was added to the page, however it didn't seem to function the same way as a google conversion code that was inserted 'normaly' would. it doesn't inject the dom with additional additional img pixels or iframes that usually get inserted to the DOM by the conversion code. I have a strong suspicion the conversion doesn't really work. – Yossi Ben Haim Apr 25 '12 at 07:08
  • Indeed, the variables need to be globals. Actually, the main reason, I think, why the "normal" script doesn't work as is in AJAX is because the variables are declared with the `var` keyword. It works in normal HTML because that declares them in the global space, whether you use var or not. – Alexis Wilke Jul 22 '12 at 00:23
  • 8
    @Yossi, my suspicions as well. I found this related article http://articles.adamwrobel.com/2010/12/23/trigger-adwords-conversion-on-javascript-event and so I analyzed the `conversion.js` script myself to verify yes, it does use `document.write` --- so the _location_ of where the script is inserted does indeed seem important. (Although, I'm not sure I feel comfortable overwriting document.write, as is suggested in his solution...) – Funka Jul 23 '12 at 23:41
  • 2nd example above should be corrected to use `var w = window; w.google_conversion_id = ""; etc.` to set variables as globals. And the code doesn't work without Adam Wrobel's fix to `document.write` – razzed Dec 11 '13 at 23:36
  • This solution does not work due to the – jonathanKingston Jan 02 '14 at 17:24
  • 10
    I would strong advise *against* any custom solutions like this - I am not sure how this got marked as the correct answer! https://developers.google.com/adwords-remarketing-tag/asynchronous/ has everything needed to do this properly. – matt1 Jan 08 '15 at 12:39
  • @matt1 will this still track a conversion even if we are not using a remarketing campaign? ie. Just a straight forward adwords campaign? – digout Jun 10 '15 at 09:33
14

this simple code worked for me (the $.getScript version didn't).

var image = new Image(1,1);
image.src = 'http://www.googleadservices.com/pagead/conversion/' + id + '/?label=' + label + ' &guid=ON&script=0';
Antoine Tissier
  • 621
  • 5
  • 13
  • I thought of doing that, but I was afraid that the `script=0` parameter at the end of the line could have a "bad" side effect. Plus, if you write that in code, it makes more sense to use the solution with JavaScript as presented by Microscopic. – Alexis Wilke Jul 22 '12 at 00:06
5

// This takes care of it for jQuery. Code can be easily adapted for other javascript libraries:

        function googleTrackingPixel() {
            // set google variables as globals
            window.google_conversion_id = 1117861175
            window.google_conversion_language = "en"
            window.google_conversion_format = "3"
            window.google_conversion_color = "ffffff"
            window.google_conversion_label = "Ll49CJnRpgUQ9-at5QM"
            window.google_conversion_value = 0

            var oldDocWrite = document.write // save old doc write

            document.write = function(node){ // change doc write to be friendlier, temporary
                $("body").append(node)
            }

            $.getScript("http://www.googleadservices.com/pagead/conversion.js", function() {

                setTimeout(function() { // let the above script run, then replace doc.write
                    document.write = oldDocWrite
                }, 100)

            })
        }

// and you would call it in your script on the event like so:

$("button").click( function() {
   googleTrackingPixel()
})
justinkempton
  • 77
  • 1
  • 2
  • I used to use a solution similar to this, but it is very hacky. //www.googleadservices.com/pagead/conversion_async.js is the way to go – Andy Zarzycki Jul 07 '16 at 21:18
4

In your Adwords account - if you change the conversion tracking event to "Click" instead of "Page Load" it will provide you with code that creates a function. It creates a snippet like this:

<!-- Google Code for Developer Contact Form Conversion Page
In your html page, add the snippet and call
goog_report_conversion when someone clicks on the
chosen link or button. -->
<script type="text/javascript">
  /* <![CDATA[ */
  goog_snippet_vars = function() {
    var w = window;
    w.google_conversion_id = <Your ID Here>;
    w.google_conversion_label = "<Your value here if any>";
    w.google_remarketing_only = false;
  }
  // DO NOT CHANGE THE CODE BELOW.
  goog_report_conversion = function(url) {
    goog_snippet_vars();
    window.google_conversion_format = "3";
    window.google_is_call = true;
    var opt = new Object();
    opt.onload_callback = function() {
    if (typeof(url) != 'undefined') {
      window.location = url;
    }
  }
  var conv_handler = window['google_trackConversion'];
  if (typeof(conv_handler) == 'function') {
  conv_handler(opt);
  }
}
/* ]]> */
</script>
<script type="text/javascript"
  src="//www.googleadservices.com/pagead/conversion_async.js">
</script>

Then in your code you just call:

goog_report_conversion();

Or for a link or image click:

<a href="" onclick="goog_report_conversion();">click here</a>
webmaster_sean
  • 942
  • 4
  • 13
  • 23
1

After trying everything the link Funka provided (http://articles.adamwrobel.com/2010/12/23/trigger-adwords-conversion-on-javascript-event) was what worked for me. Like he said it's scary to overwrite document.write, but It seems like this is what you have to do unless you can load the script before the page load.

Sabrina Leggett
  • 9,079
  • 7
  • 47
  • 50
1

Since the script uses document.write so it needs to be re-written

document.write = function(node){ // exactly what document.write should of been doing..
  $("body").append(node);
}
    window.google_tag_params = {
        prodid: pageId,
        pagetype: pageTypes[pageType] || "",
        value: "234324342"
    };
    window.google_conversion_id = 2324849237;
    window.google_conversion_label = "u38234j32423j432kj4";
    window.google_custom_params = window.google_tag_params;
    window.google_remarketing_only = true;

    $.getScript("http://www.googleadservices.com/pagead/conversion.js")
.done(function() {
      // script is loaded.
    });

See https://gist.github.com/c7a316972128250d278c

adardesign
  • 33,973
  • 15
  • 62
  • 84
1

As you have seen, the google conversion tag only calls on a redraw. I had to make sure it was called when a part of a page was redrawn. (Due to some bad website design that I could not fix at the moment.) So I wrote a function to call from an onClick event.

Essentially, all you have to do is to call doConversion();

Here is what we ended up with:

    // gothelp from from http://www.ewanheming.com/2012/01/web-analytics/website-tracking/adwords-page-event-conversion-tracking

    var Goal = function(id, label, value, url) {
    this.id = id;
    this.label = label;
    this.value = value;
    this.url = url;
    };

function trackAdWordsConversion(goal, callback) {
// Create an image
var img = document.createElement("img");

// An optional callback function to run follow up processed after the conversion has been tracked
if(callback && typeof callback === "function") {
    img.onload = callback;
}
// Construct the tracking beacon using the goal parameters
var trackingUrl = "http://www.googleadservices.com/pagead/conversion/"+goal.id;
trackingUrl += "/?random="+new Date().getMilliseconds();
trackingUrl += "&value="+goal.value;
trackingUrl += "&label="+goal.label;
trackingUrl += "&guid=ON&script=0&url="+encodeURI(goal.url);
img.src = trackingUrl;

// Add the image to the page 
document.body.appendChild(img);

// Don't display the image 
img.style = "display: none;";
    }
function linkClick(link, goal) {
try {
    // A function to redirect the user after the conversion event has been sent
    var linkClickCallback = function() {
        window.location = link.href;
    };

    // Track the conversion
    trackAdWordsConversion(goal, linkClickCallback);

    // Don't keep the user waiting too long in case there are problems
    setTimeout(linkClickCallback, 1000);

    // Stop the default link click
    return false;
} catch(err) {
    // Ensure the user is still redirected if there's an unexpected error in the code
    return true;
}
}
function doConversion() {
var g = new Goal(YOUR CODE,YOUR_COOKIE,0.0,location.href);
return linkClick(this,g);
}
BillRoth
  • 31
  • 6
1

I tried all the ways to manually include conversion.js, it all loaded the script, but didn't further execute what we needed inside the script, there's a simple solution.

Just put your conversion code in a separate HTML, and load it in an iframe.

I found code to do that at http://www.benjaminkim.com/ that seemed to work well.

function ppcconversion() {
var iframe = document.createElement('iframe');
iframe.style.width = '0px';
iframe.style.height = '0px';
document.body.appendChild(iframe);
iframe.src = '/track.html'; // put URL to tracking code here.
};

then just call ppcconversion() wherever in the JS you like to record it.

0

All I do is return the code (or in our case, an image) along with the "success" message in the callback.

When a contact form is submitted, or a registration form filled out and submitted, we post to a php script using jQuery, then output a "thank-you" message to a div:

"$first_name, Thanks for requesting more information. A representative will contact you shortly."

... followed by the 1x1 gif Google provides.

Here's the jQuery:

$.post('script.php',{'first_name':first_name,'last_name':last_name,'email':email,'phone1':phone1,'password':password,},function(data){
var result=data.split("|");
if(result[0] ==='success'){
$('#return').html(result[1] + $result[2]);

And the php...

echo 'success|'.$first_name.', Thanks for requesting more information.
A representative will contact you shortly.|<img height="1" width="1" alt="" src="http://www.googleadservices.com/pagead/conversion/xxxxxxxx/imp.gif?value=0&amp;label=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&amp;script=0"/>';

You might need to throw in a "document.location.reload();" if it isn't being picked up by google

akjoshi
  • 15,374
  • 13
  • 103
  • 121
0

For anyone still looking for a good solution to this, Google supports AJAX Conversions natively now through their Google Analytics API.

You can do it by making a event API call in Google Analytics. What you do is setup an Analytics event, tie it to a goal, then import that goal into AdWords as a conversion. It's a bit of a lengthy process but it's a clean solution.

Check out This Page for a tutorial

Community
  • 1
  • 1
Mark
  • 9
  • 1
0

This works for me:

window.google_trackConversion({
    google_conversion_id: 000000000, 
    conversion_label : "xxxxxxxxxxxx",
    google_remarketing_only: false,
    onload_callback : function(){
        //do something :)
    }
});
infinito84
  • 1,971
  • 17
  • 8