Using JSONP with 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 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’s API is:[resultsCallBack]&url=[escapedUrlToMinify]

For example the call,


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'); = 'dynScript';
   s.src = "" + url;

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