2LeggedSpider

Generating a Shorter URL using bit.ly API and jQuery

Posted in AJAX, jquery by Sumit Thomas on December 18, 2009

[tweetmeme style=”compact”]Here is a simple jQuery script to generate shorter URL using the bit.ly API.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>URL Shortening</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnShort").click(function() {
                var longUrl = $("#longUrl").val();
                var shortUrl = $("#shortUrl");
                shortUrl.html("Loading...");
                var params = {
                    version: "2.0.1",
                    longUrl: longUrl,
                    login: "bitlyapidemo",
                    apiKey: "R_0da49e0a9118ff35f52f629d2d71bf07"
                };
 
                $.getJSON("http://api.bit.ly/shorten",
                { version: params.version, longUrl: params.longUrl, login: params.login, apiKey: params.apiKey },
                function(data) {
                    shortUrl.html(data.results[longUrl].shortUrl);
                });
            });
        });
 
    </script>

</head>
<body>
    <input type="text" id="longUrl" /><input type="button" id="btnShort" value="Shorten!" />
    <br />
    <div id="shortUrl" />
</body>
</html>

URL Shortening

You can go through the bit.ly API documentation and try out the remaining methods as well.

Tagged with: , ,