Categories
Javascript

Working with the Google Chart (Visualization) JavaScript APIs

For a current project at my workplace I need a good charting solution. I need a pie chart for now, on which people can actually click and interact. I found a few tools and went for the Google Visualization APIs. The APIs are a set of JS libraries which let you build quick charts and graphics out of data tables. I started trying the sample codes on the Google Ajax playground and quickly understood which way to go to get things right. First I must make it clear that, I’m no Javascript pro. I have coded with jQuery a few times before and I have no real experience with JS until today. It is just today I spent a good amount of time with the Facebook JS APIs. Who knows if it’s the brilliant documentation at the Google Code or my fast learning ability, it took me just one hour to learn the Visualization APIs and cook something up from scratch.

Here’s the source code:

It’s very simple and easy. First we include the root javascript from: http://google.com/jsapi and then put the above codes in a script tag inside head.

We use the google loader to load the visualization package and then use it to build a PieChart. When the loading is done, the setOnLoadCallback() method invokes another function to proceed with further execution. We packed our main code inside a drawChart() function and set it as the callback.

To assemble the data, we first need a DataTable. A data table is an object with virtual columns and rows. First, we need to define the columns. We do that by calling the addColumn() method. The first parameter is the data type and the second one is the name. In our example, we added two columns.

Next, we call the addRows() passing an integer as the only parameter. This method creates “filler” or empty sets for putting data into.

Then, we use the setValue() call to insert/update data. The first parameter is the row number counted from 0. The second one is the index of column. Remember the sequence of the column definitions? Yes, follow that sequence. The first column is the index 0. The 3rd parameter is the actual value for that row and column.

The above call will insert the string “meaow” into the second column of the 3rd row. It’s easy! 🙂
PS: Please be aware of the data type of the column while inserting/updating data.

Now that we have a DataTable at our disposal, all we need to do is feed this data to a PieChart and draw it up. First, we created a new div with the id “chart”. This div will be holding the chart. Then we call the PieChart constructor with this div element. Then we call the draw() method of the chart object to paint it on the screen. The first parameter is the datatable and the second one is an object (dictionary/associative array like) defining the look and feel of the charts.

That draws the chart alright. But I need to let the users interact with the chart. So, I added a Listener to listen to any “select” events and call the handler function back. We get a event object but for select events, they don’t have any properties. That is they don’t tell you what the user clicked. You have to get the data by calling the getSelection() method of the chart. The returned object will have “row” and “column” values. For PieChart, alone the row value does the job. We get the row index. Then call the getValue() method of the data table to get the value of a certain column in a row. In this case, I just iterated over both columns. Built a text string out of the data and dynamically updated a div with that!

It’s pretty simple. It’s powerful and user friendly as well.

PS: I really liked the Google Ajax Playground. I am gonna play a lot in there from now on 🙂
I just realized I’m becoming a good coder as well. I wrote the above codes without any pretty printer or code formatter. It looks well indented to me 😀

Categories
Javascript

Using The Facebook Graph API with js-sdk : An explanatory Tutorial

The facebook Graph API has a nice Javascript SDK to build applications using JS. The most important benefit is that with JS you could tightly integrate the Facebook Graph API with your web application.

Integration is quite easy. First we add a fbAsyncInit object to the window object for asynchronous initiating. The following code snippet was borrowed from the official docs and then slightly modified:

Thanks to the elegance of Javascript, we called the newly constructed object immediately after initiating, with a callback that loaded the JS sdk on our page. We registered the auth.login, auth.logout events and for initially looking for any logged in user, we made the getLoginStatus() call. In fact this code snippet initiates the facebook access on the page. Registering the events to our custom functions, we just made sure that, we know when something important happens. While iniating, if the user is already logged in, the login() function gets called because of the getLoginStatus() call. Later, after initiating, if the user logs in or logs out, the auth.login and auth.logout events get fired. Our registered handlers will be called in those cases.

To make things easy for the end user, you can use a fb:login-button tag from FBML. I believe Facebook app developers are already aware of that. Still, I was just reminding that you can still use those tags 😀 A login button is going to help you. Because, it’s mandatory that you call the FB.login() on an user event (like button click) because most browsers won’t allow opening a popup on a non-user event.

Now the user is logged in and authorized the apps, you can start customizing your contents for the user. You can always check for available users by calling the FB.getSession() function. It returns null if no user is available, otherwise, it returns a session object with access_token, app key and secret and most importantly the user uid.

You can use the dir() function on the session object to explore it on the Firebug console.

Now, you can make calls to the Graph API using the normal path pattern:

The above code will alert() the user’s latest photo URI. Well, make sure that the applicaton has permissions to make the calls.

You can even mix up with the legacy API by passing an object with a “method” parameter pointing to the method name and related args. You can build the Facbook UIs using the FB.ui() call. Have a look how we use legacy API and UI to build a nifty sharing dialog box.

Here, instead of alert()ing the response, we logged it to the console 😀

In this way, you can interact with the user the way you want. It’s plain and simple. So, start digging now and have fun.

The Offcial js-sdk docs can be found here: http://developers.facebook.com/docs/reference/javascript/

Happy developing! Happy Facebooking! 😀 😀 😀

Categories
PHP

Using the Facebook Graph API

I caught viral fever and decided to take the day off from work. To pass my leisure I decided to play with the Facebook APIs. I noticed that Facebook Platform has changed a lot. They have released the new “php-sdk” to let the devlopers integrate facebook into their own sites. Actually, they have released SDKs for other languages too (namely Python and JS). For playing with the toys at hand, I picked up the php-sdk and started browsing through the docs. Amazingly, Facebook has launched OAuth support. I am very happy about that. I no longer need to run my applications inside the facebook frame. Rather I can customize my contents for the facebook users. This is plain cool!

I downloaded the php-sdk and started off. But soon, I faced problem. The php-sdk is not well documented (in my opinion) and I had a very hard time figuring things out. It became even worse when I failed to test some of the features which are tightly integrated deep inside facebook. For example, I couldn’t find a way to construct some advanced URLs and also the sdk was not suitable for my debugging needs. The sdk is not poor, I later found it out to be strong but the main problem is it’s not much documented.

So, to try out things and to figure out how the Facebook OAuth works, I started writing my own codes. That helped though I struggled a bit to setup permissions. When I saw that the code is working fine, I chose to pack it up in a class file and rewrite the testing environment.

It took me 30 minutes to rewrite everything up. The package now contains the library and a console to test different methods.

You can download it from: http://masnun.googlecode.com/files/facebook-graph_API-oauth.zip

Extract it into a directory on your website. Register a facebook application. Go through the traditional setup. Please remember to add your domain name on the Connect tab of the application you created 🙂 Edit the config.php and visit the index.php using your browser. You’ll be redirected to Facebook without a word. When you authorize and return, you get a fine console to test things out and see for yourself! 😀

Lets see a quick intro to the library (facebook.php) 🙂

Facebook requires you to redirect the user to an authorization URL with your client id and the callback url. So, we first do this:

You have to ask for permissions on Authorization. I couldn’t get to make the user extend permissions on the post authorization phase. So, I have included **ALL** available permissions in the config.php. Permission is what I suffered with most. If you use my library, it’ll ask the user for all permissions so that you can test everything out. I know you won’t need all those permissions in production environment. Just comment out the ones you don’t want!

Facebook returns the user to the $callback_url with a GET parameter named “code” with others. By using this code with the application secret and callback url, we can get the access_token for the user 🙂 We can do that easily using the client :

getAccessToken() retrieves the access_token from the facebook server. setAccessToken() adds the token to the facebook object and makes it ready to make api calls.

The $data is an array with the keys – access_token and expires. After we set the access token, we can make API calls from the client. For the details on API Paths, please visit: http://developers.facebook.com/docs/api 🙂

I really liked the new structure of the facebook API. The previous API was bloated and sometimes very hard to implement. I do thank Facebook very much for making things easy for the developers!