Tag Archives: jquery

Integrating InMobi Ads into jQueryMobile and MoSync based app

Recently I was developing a HTML5 app for a client using jQueryMobile and MoSync Reload with Wormhole Library (an amazing client which let you develop about 70% times faster compared to using native procedures) when I struck with a problem of placing InMobi ads into jQueryMobile sub-pages. If you are familiar with jQueryMobile you would know that it normally fetch pages on ID bases through AJAX and this trick allows it make smooth transitions. While on non-AJAX pages you can simply integrate InMobi’s JavaScript SDK which would be simple JavaScript snippet which you include in your pages and mobile ads will start rolling, however, in case of  AJAX based pages, ad providers normally detect AJAX requests and then refuse to serve ads because of the threat of misuse. I went as far as signing up for an AdMob account but found similar problem there.

I googled through, despite of some questions on stackoverflow, none had the solution (except the solution of turning to non-AJAX based pages which I couldn’t do in any case), I fired up an email to InMobi support and surprisingly got reply with-in an hour linking me to InMobi Mobile Web API.

InMobile Web API require POST request with a certain set of parameters and then return ads in XML format which you then need to parse and display ads wherever you want (including your jQueryMobile sub-pages).

Following is the dissection of request to API:

Basically InMobi Mobile Web API require you to make a POST request along with following parameters:

mk-siteid=xxxxxxXXXXXxxxxxXXXXXX&
mk-version=pr-SPEC-ATATA-20090521&
h-user-agent=Nokia6233%2F2.0&
mk-carrier=117.97.87.6&
format=xml
  • mk-siteid is the ID which you get after registering your app with InMobi through their website, for the purpose of development you can use their test ID which is: 4028cba631d63df10131e1d3191d00cb
  • mk-version is unknow to me but it remains static as it is.
  • h-user-agent is your browser agent which you can easily get through navigator.userAgent
  • mk-carrier is the user IP which you can get through following simple JSON call:
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data){
      userIP = data.ip;
});

and format can always be XML as response will always be.

Moving forward we all know how to make POST request using jQuery along with above parameters:

$.post("http://w.sandbox.inmobi.com/showad.asm", { "mk-siteid": "4028cba631d63df10131e1d3191d00cb", "mk-version": "pr-SPEC-ATATA-20090521", "h-user-agent": navigator.userAgent,
"mk-carrier": localStorage.getItem("userIP"), format: "xml", "mk-ad-slot": 10 },
function(data) {
         console.log(data);
}

URL in above post request is of Sandbox which you should use while developing and when you are ready to go Live, you should make your calls to:

http://w.inmobi.com/showad.asm

At this point if you check your Firebug or Chrome JavaScript developer tools you should see a XML object with AdURL, ImageURL or LinkText in it. The next step would be how we extract this data and display in our page.

First you need to create an ad ‘holding’ area in HTML, in my case I created it just above the closing content div:

<div>
<a id="bannerURL" href=""><img id="playerBanner" src=""></img></a>
</div>

Next you need to expand your data callback function and include XML parsing capability which should extract the ad data out and show it in ad holding HTML.

function(data) {
        $(data).find("Ad").each(function(){ //find Ad tag and loop through each
        $("#bannerURL").attr("href", $(this).find("AdURL").text()) ;  //get AdURL tag and update 
        if($(this).attr("type") != "text"){ //if ad is not text based
           $("#playerBanner").attr("src", $(this).find("ImageURL").text()) ; //update image src 
        }else{ //in case of text based ad
           if($(this).find("LinkText").text() != "invalid ip-address"){ //ip not found
              $("#bannerURL").text($(this).find("LinkText").text()) ; //just update text
           }
        }
        });
}

Above code should be self explanatory as I have added comments against each line, basically you need to loop through all of the XML, finding “Ad” nodes, then going through each node and finding AdURL (where user will go after clicking on Ad) and updating href attribute of our hyperlink tag in holding HTML then InMobi serve ads in two formats, one is text and other is image based banner ads. If it’s not text ad, we will get ImageURL and update the img src in our holding HTML, if it’s text ad then we will simply update text enclosed in “a” tags.

This should complete your ad integration and you should see a sandbox banner or text in your sub-pages. In my case it did:

Complete code is below:

<script>
var userIP;
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data){
        userIP = data.ip;
        localStorage.setItem("userIP", userIP);
});

$.post("http://w.sandbox.inmobi.com/showad.asm", { "mk-siteid": "4028cba631d63df10131e1d3191d00cb", "mk-version": "pr-SPEC-ATATA-20090521", "h-user-agent": navigator.userAgent,
"mk-carrier": localStorage.getItem("userIP"), format: "xml", "mk-ad-slot": 10 },
function(data) {
        $(data).find("Ad").each(function(){ //find Ad tag and loop through each
        $("#bannerURL").attr("href", $(this).find("AdURL").text()) ;  //get AdURL tag and update 
        if($(this).attr("type") != "text"){ //if ad is not text based
           $("#playerBanner").attr("src", $(this).find("ImageURL").text()) ; //update image src 
        }else{ //in case of text based ad
           if($(this).find("LinkText").text() != "invalid ip-address"){ //ip not found
              $("#bannerURL").text($(this).find("LinkText").text()) ; //just update text
           }
        }
        });
});
</script>
<div>
<a id="bannerURL" href=""><img id="playerBanner" src=""></img></a>
</div>

This provides basic integration of ad API and you can build your ad serving structure on top of it. One improvement would be of adding your in-house ads which would show banners linking to your other apps probably as often InMobi simply do not return any ad when you go live, instead it would show:

<!-- mKhoj: No advt for this position -->

So, it would be wise to handle this exception and in this case show your own ad.

Happy coding!

 

 

YUI Panel: Changing buttons and re-using a panel on same page

YUI is a natural Javascript library, it is different from jQuery and other Javascript frameworks due to its closeness to original JS where it supports you to build widgets and enhance the user experience, the other JS libraries such as jQuery and Dojo are incredibly easy to work in but they divert you so much from the original language that they become almost a language of their own. The closeness of YUI to the Javascript at the one end gives you the depth to work at your own ease and develop whatever you want, on the other hand it proves to be a bit difficult for the beginners, probably that is the reason, you will not find much support for YUI around, YUI has its own forums where the original developers of YUI reply in time-efficient manner as well but they speak at very high level and people to support at beginner and middle level are very less on Google.

So, I have decided to write some blog posts about the problems I faced and I was not able to find help on Google but then I figured out in some way (occasionally from the help of developers at yuilibrary.com where I got some hints and I made something out of it). I have already wrote first in this series which was about IE rendering problem in YUI tabs, today I will explain how you change modal panel buttons on the fly.

The requirement was to make a modal panel in YUI, which work at its own as a activation widget using Ajax (YUI connection manager). The idea was pop up a YUI panel when a user clicks on “Activate”, that modal panel will allow the user to enter details of when he/she wants to schedule the activation (where user can choose now or a later date) and then user can hit Submit and Cancel buttons. Uptil now its usual YUI panel which you will find in any YUI panel example, here is the example of making this panel:

//function to execute if user clicks on Cancel button
var handleCancel = function() {
 this.cancel();
 };

// Instantiate the Dialog
 var dialog23 = new YAHOO.widget.Dialog("dialog23",
 { width : "340px",
 fixedcenter : true,
 visible : false,
 modal: true,
 constraintoviewport : true,
 hideaftersubmit: false,
 buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
 { text:"Cancel", handler:handleCancel } ]
 });
//delcare the call back
dialog23.callback = { success: handleSuccess,
 failure: handleFailure };
 // Render the Dialog
 dialog23.render(document.body);

//attach the listener to Activate (button, div,
//span where ever you want to attach the click listener)
YAHOO.util.Event.addListener("Activate", "click",
dialog23.show, dialog23, true);

A function of handleSuccess is missing in this example, I will leave that to you because in my code its very inter-related. The handleSuccess is where I make an Ajax request through YUI connection manager, once the request get submitted, I show a spinning wheel and then the Ajax response get shown to the user. The problem here is, you can easily show the response but changing the buttons at the bottom became a night-mare. Once the response is shown, you don’t really want to show the user Submit, Cancel buttons, what you really need there is a OK button so that user can acknowledge and on acknowledgment the panel hides away.

Here is how you change the button at the bottom of YUI panel:

//embed the OK button, on click handleOK function will be called
 dialog23.cfg.setProperty("buttons", [ { text:"OK",
handler:handleOK, isDefault:true }]);

and then write a funciton to act when user press Ok

//these are events which happen after a user clicks OK
 var handleOK = function() {
 //hiding the dialog box
 dialog23.hide();
 };

There is one other approach I am using in this panel, that is if once activated, the user clicks on the Activate/Deactivate button again, what will happen then? You really need to make it dynamic.

For example your panel HTML was this:

<div id="dialog23">
<div>Activation</div>
<div align="left"><div id="ajaxResponse">
<form method="POST" action="timeschedule.php">
 <input type="hidden" name="buttontime" value="1">
 <div id="resp"></div>
<div>Enter the date here: <input type=text value=date name=date>
</div>
</form>
</div></div>
</div>

In this case before initializing anything get the all the ajaxResponse innerHTML in a variable like:

var div = document.getElementById('ajaxResponse');
//we are storing schedule HTML which we will restore at the end
var divHTML = div.innerHTML;

Now our ajax response will change the bits you get in ajaxResponse div, the input text box and other will be changed something like:

User specified action has been activated.

What you need now is to restore the original panel just when the user clicks OK, the handleOK function will get changed to this:

//these are events which happen after a user clicks OK
 var handleOK = function() {
 //restore the schedule HTML in case user wants to use it again
 div.innerHTML = divHTML; //populating the initial schedule HTML back
 //hiding the dialog box
 dialog23.hide();
 //rebuilding the submit and cancel buttons for re-use
 dialog23.cfg.setProperty("buttons", [ { text:"Submit",
handler:handleSubmit, isDefault:true },
 { text:"Cancel", handler:handleCancel } ] );
 };

And here you will replace the buttons in the bottom of the panel again to Submit and Cancel.

I have elaborated enough here to give you an idea of how things work, its possible you are not working on same thing but my idea was really to give you ability to change buttons in the panel on the fly and to give you an idea that how you can use a panel again and again. If you need any further help, don’t hesitate to comment and I will try to reply as much as I can.

Get Adobe Flash player