Loading ...

How to shorten url with jQuery | CodeAsp.Net

How to shorten url with jQuery

3.65 
 /5
3.65 (1votes)

In this article I will show how to shorten url with jQuery. I am going to use bit.ly api to shorten the urls. I have made a custom jQuery plugin which will use bit.ly API to shorten the longurl. URL shortening is a technique on the World Wide Web in which a URL is  made shorter in length. An HTTP Redirect is made from short name link domain to the original link. For example, the URL http://codeasp.net/articles/asp-net/222/how-to-shorten-url-with-jquery can be shortened to http://bit.ly/fXRJZP.

First of all get your own api key and login. You can get your apikey from http://bit.ly/a/your_api_key/ . In this example I am going to use a sample account :

UserName: testuserforshortening
API Key: R_db8dcbb3ba3bc504c5dab1cf23878d09





I have made a custom jQuery plugin for Url shortening purpose. Below is the source code for the Url shortner plugin.

Plugin:

/*
* Url shortner using bit.ly API
* version: 1.0 (12/25/2008)
* @requires jQuery v1.2 or later
*
* Examples at http://codeasp.net/articles/asp-net/222/how-to-shorten-url-with-jquery
*
* Licensed under the MIT: http://www.opensource.org/licenses/mit-license.php
* Original Author: Raghav Khunger
* Usage:
*   $.shortenURL(longUrl, function (data) {
*       var shortUrl;
*       if (data.status_code == 200) {
*       //success
*           shortUrl = data.data.url;
*       }
*       else {
*          alert(data.status_txt); //if error show the error
*       }                  
*   });
*/

$.extend({
    shortenURL: function (longUrl, params, callback) {
        ///	<summary>
        ///	 Convert the long url to short url
        ///	</summary>
        ///	<param name="longUrL" type="String">The long url which is to be shorten</param>
        ///	<param name="params" optional="true" type="Options">A set of key/value 
        /// pairs that configure the request sent to bt.ly account</param>
        ///	<param name="callback" type="Function">A function to be executed whenever 
        /// the shortenURL function completes</param>
        ///	<returns type="XMLHttpRequest" />

        var defaults = {
            login: 'testuserforshortening',
            apiKey: 'R_db8dcbb3ba3bc504c5dab1cf23878d09'
        };


        // If the second parameter was provided
        if (params) {
            // If it's a function
            if ($.isFunction(params)) {
                // We assume that it's the callback
                callback = params;
                params = null;
            }
        }


        var opt = $.extend({}, defaults, params);

        var url = 'http://api.bit.ly/v3/shorten?'
+ '&login=' + opt.login
+ '&apiKey=' + opt.apiKey
+ '&longUrl=' + encodeURIComponent(longUrl)
+ '&history=0'
+ "&format=json&callback=?";

        return $.getJSON(url, function (data) {
            callback.call(this, data);
        });
    }
});



Above the plugin demands three params:
longUrL: The long url which is to be shorten
params (optional): A set of key/value pairs that configure the request sent to bt.ly account 
callback: A function to be executed whenever the shortenURL function completes

You can use the plugin in this way:

   $.shortenURL(longUrl, function (data) {
       var shortUrl;
       if (data.status_code == 200) {
       //success
           shortUrl = data.data.url;
       }
       else {
          alert(data.status_txt); //if error show the error
       }                  
   });


i.e the data.data.url contains the short url extracted from long url. In the above plugin if you omit the params parameters to pass which is optional, the plugin will assumes the second param as the callback function. This is decided by the following code:

// If the second parameter was provided
        if (params) {
            // If it's a function
            if ($.isFunction(params)) {
                // We assume that it's the callback
                callback = params;
                params = null;
            }
        }



Now let's come to some sample code in order to to test the plugin. Below is the full sample source code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" 
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript">
/*
* Url shortner using bt.ly API
* version: 1.0 (12/25/2008)
* @requires jQuery v1.2 or later
*
* Examples at http://codeasp.net/articles/asp-net/222/how-to-shorten-url-with-jquery
*
* Licensed under the MIT: http://www.opensource.org/licenses/mit-license.php
* Original Author: Raghav Khunger
* Usage:
*   $.shortenURL(longUrl, function (data) {
*       var shortUrl;
*       if (data.status_code == 200) {
*       //success
*           shortUrl = data.data.url;
*       }
*       else {
*          alert(data.status_txt); //if error show the error
*       }                  
*   });
*/

$.extend({
    shortenURL: function (longUrl, params, callback) {
        ///	<summary>
        ///	 Convert the long url to short url
        ///	</summary>
        ///	<param name="longUrL" type="String">The long url which is to be shorten</param>
        ///	<param name="options" optional="true" type="Options">A set of key/value 
        /// pairs that configure the request sent to bt.ly account</param>
        ///	<param name="callback" type="Function">A function to be executed whenever 
        /// the shortenURL function completes</param>
        ///	<returns type="XMLHttpRequest" />

        var defaults = {
            login: 'testuserforshortening',
            apiKey: 'R_db8dcbb3ba3bc504c5dab1cf23878d09'
        };


        // If the second parameter was provided
        if (params) {
            // If it's a function
            if ($.isFunction(params)) {
                // We assume that it's the callback
                callback = params;
                params = null;
            }
        }


        var opt = $.extend({}, defaults, params);

        var url = 'http://api.bit.ly/v3/shorten?'
+ '&login=' + opt.login
+ '&apiKey=' + opt.apiKey
+ '&longUrl=' + encodeURIComponent(longUrl)
+ '&history=0'
+ "&format=json&callback=?";

        return $.getJSON(url, function (data) {
            callback.call(this, data);
        });
    }
});


$(function () {

    $('#<%= btnShorten.ClientID %>').click(function () {
        $('#<%= lblShortUrl.ClientID %>').html('Shortening... ');
        var longUrl = $('#<%= txtLongUrl.ClientID %>').val();
        $.shortenURL(longUrl, function (data) {
            var url;
            if (data.status_code == 200) {
                url = data.data.url;
            }
            else {
                url = data.status_txt; //if error show the error
            }
            $('#<%= lblShortUrl.ClientID %>').html(url);
        });

        return false;
    });

});

    </script>
</head>
<body>
    <form id="form1" runat="server">
    Long Url:
    <asp:TextBox ID="txtLongUrl" runat="server" Width="500px"></asp:TextBox>
    <br />
    <asp:Button ID="btnShorten" runat="server" Text="Shorten the Url" />
    <br />
    Short Url:
    <asp:Label ID="lblShortUrl" runat="server" Text=""></asp:Label>
    </form>
</body>
</html>


Above I have used one textbox (for long url), one button and a label. On clicking the button the long url present in the textbox will be converted to short url. This is done with the following code:

$(function () {

    $('#<%= btnShorten.ClientID %>').click(function () {
        $('#<%= lblShortUrl.ClientID %>').html('Shortening... ');
        var longUrl = $('#<%= txtLongUrl.ClientID %>').val();
        $.shortenURL(longUrl, function (data) {
            var url;
            if (data.status_code == 200) {
                url = data.data.url;
            }
            else {
                url = data.status_txt; //if error show the error
            }
            $('#<%= lblShortUrl.ClientID %>').html(url);
        });

        return false;
    });

});



Output:



Here is the info of some status codes returned from bit.ly API:
http://code.google.com/p/bitly-api/wiki/ApiDocumentation

  • json { "status_code": 200, "status_txt": "OK", "data" : ... }
  • json { "status_code": 403, "status_txt": "RATE_LIMIT_EXCEEDED", "data" : null }
  • json { "status_code": 500, "status_txt": "INVALID_URI", "data" : null }
  • json { "status_code": 500, "status_txt": "MISSING_ARG_LOGIN", "data" : null }
  • json { "status_code": 503, "status_txt": "UNKNOWN_ERROR", "data" : null }
  • jsonp callback_method({ "status_code": 200, "status_txt": "OK", "data" : ... })



That's it we are done with how to shorten url with jQuery using bit.ly API. Do let me know your feedback, comments.

                                                                     

Comments (3)

   
hajan
I read your blog yesterday. It's excellent I must say.
12/29/2010
 · 
by
   
Manchun

this is nice article about short url thank you.

1/9/2017
 · 
by
   
JanBask

this is nice article. thank you.

1/10/2017
 · 
by
  • :*
  • :*
  • :
 *

Top Articles