A couple of days ago, I started implementing a rather interesting piece of code. It was late into the night, and I was not feeling like doing my regular work and neither was I sleepy.
Nothing is probably more frustrating for a developer than a framework/api providing some feature but not documenting it. No doubt, this would have happened to you multiple times. For me, two very different frameworks (well one was a framework and the other an api) posed the challenge over the last week to explore them without complete documentation.
I wanted all YouTube interaction to happen completely client-side without involving our web-server and that was technically feasible too with YouTube providing a JSON-C api, that's basically a JSONP request returning information to a callback function.
The usual process of searching videos, suggesting related videos, playlists, feeds etc. went pretty smooth with JSON-C reference providing adequate documentation on request and response formats. And after doing all this in a pretty quick time (thanks to the excellent api), I briefly found myself stuck and scratching my head with the question on how to retrieve a particular video's details after I had its id.
According the the JSON-C reference, the supported operations are for video search results, feeds, playlists, adding/removing videos etc. but the option for retrieving a particular video's details was nowhere to be found on the JSON-C reference page.
But I saw similarities in the JSON-C reference and the Data API protocol to fetch data for a single video. I just hoped that appending JSON-C parameters to the Data API protocol (alt=jsonc and a valid callback method name) might make it work in pure js. And to my relief, it did when I tried it out.
You can test the same in the example below, try entering any valid YouTube video id in the textbox and click "Get Video Information". You should see an alert with the serialized information returned by YouTube:
When you click the "Get Video Information" button, the correspondingly named js method gets called. It creates a request url starting with "https://gdata.youtube.com/feeds/api/videos/" (the base url for all YouTube Data api requests), appends the YouTube video id it to, adds the "alt=jsonc" query-string parameter that requests the api to return json-c response and finally the callback parameter which specifies the method name to invoke when the response arrives (this should be a globally scoped method name, and not a local variable or method reference). You can see clearly that this is a regular JSONP request.
Tada, when the response arrives, the videoInfoCallback method checks for any error or else displays the serialized information in an alert box (you would obviously show the returned information to the user in a more friendly way).
registerScript is a utility method that accepts a url, creates a <script> tag for it and adds it to the page.