jQuery: creating a tiny URL

In this post I'm going to show you how to create a tiny URL with jQuery and the aid of PHP. In fact, the code is split into two components: the jQuery part and the PHP script. The PHP script simply uses the TinyURL APIs to convert a GET parameter passed by jQuery into a brand new tiny URL. Since we don't want this parameter to be spoofed, we also perform a regular expression check on the URL passed by jQuery. As some of you may have guessed, we're going to use an AJAX method of jQuery to pass the URL to the PHP script. First of all, here's the PHP script, called tinyurl.php:

<?php
header('Content-Type: text/plain');

$uri = $_GET['u'];

if(!preg_match('#https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?#', $uri)) {
   echo 'Not a valid URL.';
   exit();
}

function createTinyURL($url) 
{
    $tinyurl = file_get_contents('http://tinyurl.com/api-create.php?url=' . $url);
    return $tinyurl;
}

echo createTinyURL($uri);
?>

As you can see, the createTinyURL() function get the resulting tiny URL from the TinyURL APIs. Note how the output will be in plain text, just to speed up parsing a little bit. Now jQuery:

$(document).ready(function() {

    var uri = $('#test').find('a').attr('href');



    $.ajax({
        type: 'GET',
        url: 'tinyurl.php',
        data: 'u=' + uri,
        success: function(tinyurl) {
        
            $('<a/>').attr('href', tinyurl).text(tinyurl).appendTo('#result');
        
        
        
        }
        
   });





});

We use the $.ajax() wrapper here by passing the u GET parameter along with our AJAX request. This parameter will contain the URL we want to shorten (in this case, the href attribute of a link). You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.