JSON Callback Example

In this post, we give an example on how to integrate an affinitAD widget using the “Json Callback” method.
The main interests of this method are:

  • ability to provide the affinitAD Web Service with a keyword to search for (using the “kw” parameter)
  • more control on the widget display (error code handling, ability to set timeout, …)

The principle is the following:

  • a call is made towards the widget API, specifying a callback function in the “callback” parameter
  • the specified js function is called with a JSON answer as parameter

Now, let’s look into that more precisely.

Calling URL

<script type="text/javascript" src="http://wtpn.twenga.##TLD##/Publisher/Api/widget
?key=##PUBLIC_KEY##
&amp;confkey[]=##CONFIG_KEY##
&amp;kw=##KEYWORD##
&amp;callback=##CALLBACK_FUNCTION##"></script>

where the parameters are the following:

Parameter Mandatory Description
key Yes ##PUBLIC_KEY## is specific to each Publisher
confkey[] Yes ##CONFIG_KEY## identifies a given Widget
kw Yes ##KEYWORD## is the product to search for.
callback Yes ##CALLBACK_FUNCTION## is the name of the JavaScript function to which the JSON-formatted answer will be sent.

JSON Answer

##CALLBACK_FUNCTION##({
   "result": 1,
   "iframes": [{
      "confkey": "##CONFIG_KEY##",
      "html": "<iframe height="240" width="320"></iframe>;

Attribute description:

Attribute Mandatory Description
result Yes 1:some offers where found. 0: an error occurred
errorCode No A numeric error code
errorMessage No A human-readable error message
iframes No a table of ‘iframe’ whose description is given below

iframe attribute description:

Attribute Mandatory Description
confkey Yes Configuration Key associated with the widget
html Yes HTML code for the iframe to be inserted in the page
twurl Yes URL pointing to a category or search page on Twenga web site

The callback function

Here is the simple callback function used on this page.

function displayWidget(json){
   if( json.result == 0 ) {
      console.log("No widget!!"); 
   } else {
      for(var i in json.iframes) {
         console.log(json.iframes[i]);
         $("#iframeContainer").html(json.iframes[i].html);
         try {
            console.log("Widget added : " + json.iframes[i].confkey);
         }
         catch(e){
         }
      }
   }
};

What does it do ? Quite simple:

  • If there’s no result (json.result == 0), we log some debug information.
  • Else, we go through all the json.iframes (in fact, there can be only one in the current release) to get its html content.
  • The content is used to replace the inner HTML of a specific div present in the page.
    Note that the <div id="iframeContainer"></div> initially contains an image used as a failover in case the keyword search returns no result.

Et voilà !