Back to the Konsensys

Back to Tips
How to use Google Adsense in AJAX and HTTP POST Applications
by
George Van Treeck

Google Adsense is Google's advertisng program for "publishers" of web pages. Google Adsense provides some JavaScript code that you can embed into your web pages to display advertisements. When a vistor to your web page clicks one of the ads you get a little money from Google.

When your web page with Google Adsense ads are displayed the first time, Google crawls your web page to find salient key words to provide ads related to the content on your web page. It uses a cache of your web page, so if you change your page, the ads won't change -- so get it right the first time...

The problem with using AJAX and HTTP POST, is that the URL does not change, so different pages all appear as a single page to Google's crawler. Worse, with AJAX, loading in a new Adsense ad won't display because new JavaScript loaded by AJAX does not get executed.

In the article, JavaScript and AJAX I describe how to execute AJAX-loaded JavaScript. But, that won't help in this case, because Google's JavaScript is location dependent.

So, here is how I do it for my applications using AJAX:

1) Create an IFRAME that is larger than your Google Adsense ad.

<iframe id="my_ad" src="" scrolling="no"
    frameborder="0" style="margin: auto;
    text-align: center; width:165px; height:610px;
    border: none;"/></iframe>

2) After every AJAX call, set the IFRAME's src attribute:

getElementByID("my_ad").src=my_ad_url;

"my_ad_url" should be the URL of a web page that contains the JavaScript that Google supplies plus some keywords to help Google's web crawler target the ad better.


Copyright (C) 2010 George Van Treeck. All rights reserved.