glasses-logo

<dominikgorecki> Web development on the Microsoft Stack <dominikgorecki>

Using JSONP with b1t.co API to Shorten URLs using JavaScript only

I thought that this would be a great post to go over an easy implementation of JSONP, and also the b1t.co API (for JSONP). If you do not want to invest the time and energy in creating some AJAX proxy server-side implementation, there’s a great work around the cross-domain AJAX call issue.

It’s simple:

  1. You create a function that creates a JavaScript script that points to the web service of another domain
  2. You implement a callback funtion that does something with the returned JSON
  3. When the JavaScript script get’s “loaded” (aka, when the web service returns the JS response), it will call the callback function.

An Example

The url for b1t.co’s API is: http://b1t.co/Site/api/External/MakeUrlWithGet?callback=[resultsCallBack]&url=[escapedUrlToMinify]

For example the call, http://b1t.co/Site/api/External/MakeUrlWithGet?callback=whateverJavascriptName&url=google.com

whateverJavascriptName({"success":true,"url":"http://google.com","shortUrl":"http://b1t.co/54"});

And as soon as it loads, it will run the function, whateverJavascriptName with the JSON as it’s parameter.
So with that knowledge, let’s say that you want to implement a function minify(urlToMinify) that will run the function, minifyResultCallBack(data).

Here is the first function–it creates the JS file, sets the “src” following the API and put’s it in the header:

function minify(urlToMinify)
{
   url = escape(urlToMinify);
   var s = document.createElement('script');
   s.id = 'dynScript';
   s.type='text/javascript';
   s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
   document.getElementsByTagName('head')[0].appendChild(s);
}

Implementing the callback

This function will be run as soon as the JavaScript source of the above call gets loaded. So do what you will with the data:

function minifyResultsCallBack(data)
{
    document.getElementById("results").innerHTML = JSON.stringify(data);
}

Fin. You’re done. Simple, right? Almost simpler than AJAX.

In this example, I solely use JavaScript; jQuery has a useful JSONP implementation that automatically creates and names the callback functions. I will write about us jQuery for JSONP sometime in the future.

If you’re interested in the full source code of the above example, you can get it here: test JSONP Source

One Response to “Using JSONP with b1t.co API to Shorten URLs using JavaScript only”

Leave a Reply

Open Menu Button