Making an OpenSocial AJAX Request

March 12th, 2008 by Erik

OpenSocial Logo After much frustration debugging a tweak from OpenSocial 0.6 to 0.7, I decided I’d capture the essence of my code in one location for others to look at it. This walks through the basic structure to make an AJAX request using MySpace’s implementation of OpenSocial. It should work with other OpenSocial 0.7 compliant sites as well.

This is the core of the functionality - where all the magic happens - a function called ajaxRequest(). As you see it takes 3 parameters, the URL to post to, a call back function and an object/array containing any data you would like passed via post.

function ajaxRequest(url, callback_func, post_params){
   var queryString = "";
   for (k in post_params) {
      queryString += "&" + k + "=" + encodeURIComponent(post_params[k]);
   }
   var osParams = {};
   osParams[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
   osParams[gadgets.io.RequestParameters.POST_DATA] = queryString;
   osParams[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
   gadgets.io.makeRequest(url, makeRequest_callback, osParams);
   function makeRequest_callback(data){
      renderStatus("Handling ajax response with typeof: " + typeof(data.data));
      var json = gadgets.json.parse(data.data);
      if(!json){
         alert('Unable to parse JSON object');
      }
      callback_func(json);
   }
}

Now that we have this tool, using it is very simple, first create a call back function that takes your JSON result and does something with it, then invoke the ajaxRequest by calling the ajaxRequest function using your parameters. That’s it.

function ajax_callback(jsonData){
   // do something with the data!!!
}

ajaxRequest("http://www.af-design.com/", ajax_callback,{});

I hope this saves some developers some frustration reading through the OpenSocial documentation and helps them get their apps up and running more quickly.

Tags: , ,

One Response to “Making an OpenSocial AJAX Request”

  1. AF-Design » OAuth - A Great Pain on MySpace AF-Design » OAuth - A Great Pain on MySpace Says:

    [...] especially with MySpace’s implementation of OpenSocial and OAuth. Yesterday I blogged about how to make AJAX requests using OpenSocial. As a habit, I always default requests to POST when possible to get around any [...]

Leave a Reply

© 1998-2008 AF-Design, All rights reserved.