Gadgets Example 3… A big leap forward

The last example was a pretty simple increment from the first.  This one is going to go full throttle and add the content API call and the rendering to deal with it.  Some new stuff you might see is the use of JQuery’s .each() function and the console.log() function. .each() (see here ) is used a lot when using JQuery. It allows you to iterate through arrays and even multiple instances of html objects that match a query. For example, if you have 10 elements that have the class “coolStuff”.  You can use $(“.coolStuff”).each(function(){stuff you want to do}); to iterate through each element.   Note: to access the actual element in your function use the this object.  One other thing that is super helpful is the console.log() call. If you’re using Firebug for FireFox, this call will print to the FireBug Console. If you aren’t using FireBug in FireFox, then you really need to start :) . Get it here!

So here we go..  All I really added was a couple more functions, a  number of results global variable, and my api key as a global variable.  As for the new funcitons, one makes the call to the content API and the other handles the response.  The console.log(text) call will show you what actually comes back from the Content API call. This can be useful to see what the data actually looks like, but once you know, you should probably get rid of it.   If you aren’t familiar with the JSON part of the code, don’t worry, I’ll try to follow up with an intro to basic JSON, or you can ask me tomorrow at the hack :) .

<?xml version=”1.0″ encoding=”UTF-8″?>

<Module>
<ModulePrefs
        title="SciVerse Examples - Content API Call 1"
        title_url="http://developer.sciverse.com"
        author_email="you@you.com"
        description="Intro to Gadgets">
    <Require feature="opensocial-0.9" />
    <Require feature="sciverse" />
    <Require feature="hub" />
    <Require feature="dynamic-height"/>
    <Require feature="org.jquery.core-1.4.2" />
</ModulePrefs>

<Content type="html" view="profile,canvas"><![CDATA[

<style>
	 #content_div{
		padding-top:15px;
	 	text-align:center;
		font-weight:bold;
	 }

	 .red{
	 	color:red;
		text-decoration:underline;

	 }

</style>

<script type="text/javascript" >  

	// global variables
	var myapikey = "30b684c9d37d7c9805e77d106a344df2";
	var context;
	var authTok;
	var searchTerms;
	var numberOfSearchResultsToReturn = 50;

	//The URL for the content API search call
	var apiSearchURL = "http://api.elsevier.com/content/search/index:";

	/**
	 * 'run' is called when the 'onload' event is triggered after the page finished loading
	 */
	function run()
	{
		// the getContextInfo is a framework API call that returns the ContextInfo object.
		// @see http://developer.sciverse.com/framework#context
		gadgets.sciverse.getContextInfo(init);
	}

	/**
	 * 'init' initializes the gadget. it sets the user's search term as the default search term.
	 * this is called when the contextInfo call above succeeds.
	 */
	function init(data){
		context = data;
		searchTerms = context.searchTerms;
		authTok = context.secureAuthtoken;
		makeContentApiCall();
	}

	/**
	* Prepare to make the content api call.
	*/

	function makeContentApiCall()
	{
		//get the search terms
		var SDSearchString = searchTerms;

		//url encode them so they don't mess up the html request
		SDSearchString = encodeURIComponent(SDSearchString);

		var nrOfResults = numberOfSearchResultsToReturn;
		var view = "COMPLETE";

		//the cluster or index we want to search against.
		var cluster = "SCIDIR";

		var search = apiSearchURL + cluster + "?query=" + SDSearchString + "&count="+nrOfResults+"&view="+view;

		//setup the authentication part of the call.
		/**You must have a apikey AND authtoken for content api calls**/
		var requestHeaders = {};
		requestHeaders['X-ELS-APIKey'] = myapikey;
		requestHeaders['X-ELS-Authtoken'] = authTok;
		makeApiRequest(search, apiResponse, requestHeaders);         

	}

	function makeApiRequest(url, callback, requestHeaders)
	{
	    var params = {};
	    params[gadgets.io.RequestParameters.HEADERS] = requestHeaders;
	    gadgets.sciverse.makeRequest(url, callback, params);
	}

	function apiResponse(obj){
	    var output = "";

	    if(obj == null){
		//if there is no response then we had an error
		var display = "<b><font color='red'>return object == null</font></b>";

		//use JQuery to set the html for the div
		$('#content_div').html(display);
		return;
	    }

	    var text = obj['text'];

	    // @see http://wiki.opensocial.org/index.php?title=Gadgets.json_%28v0.9%29
	    var textJson = gadgets.json.parse(text);

	    console.log(text);

	    //is there even any results?
	    if(!textJson){
		var display = "<b><font color='red'>parsing results returned nothing</font></b>"
		$('#content_div').html(display);
		return;
	    }

	    // @see http://www.json.org/js.html
	    var entries = textJson['search-results']['entry'];
	    numberOfEntries = entries.length;
	    output = output + "<b>number of entries: " + numberOfEntries + "</b><br>";

	    // @see http://api.jquery.com/jQuery.each/
	    $.each(entries, function(i1, entry){
		var title = entry['dc:title'];
		output = output + (i1+1) + ". " + title + "<br>";
	    });

	    $('#content_div').html(output);
	}

	// @see http://wiki.opensocial.org/index.php?title=Gadgets.util_%28v0.9%29#gadgets.util.registerOnLoadHandler
	//regester the onload function. When the page is fully loaded it will call this function
	gadgets.util.registerOnLoadHandler(run);

</script>

	<div id="content_div" style="font-size: 10;"></div>

]]></Content>

</Module>