Dynamic TinyURL Links Generator using jQuery

by Jake Rocheleau

August 23, 2012 in Tutorials

There are so many web applications available for shortening URLs to share online. TinyURL is one of the originals and has been around longer than I can even remember. Their service is always online and it works perfectly for translating into tweets or posts on Facebook.

In this tutorial I want to build a mini-app which will generate tiny URLs right from your web browser. You could install this script on any domain and you’ll be able to generate dynamic links using Ajax without even refreshing the page! Their service doesn’t have a detailed API but it’s enough that we can pass a full URL and get the tiny version back as a result. And that’s just enough functionality for this app to hold some value when hosted on a 3rd party website.

TinyURL Links Generator with Ajax - preview

Setting the Page Defaults

My index page is very simple with just a single input field and one anchor link for submissions. The default input field has placeholder text letting you know we’re looking for an HTTP hyperlink.

<div id="w">
  <h1>Enter a URL below and we'll give you the tinyurl!</h1>
	
  <center><input type="text" id="url" class="biggie" placeholder="http://"></center>
	
  <a href="#" class="submitbtn" id="submitbtn">Shorten URL</a>
  <img src="images/loader.gif" alt="loader" id="loading">
	
  <div id="response">   </div>
</div>

I’ve also got two hidden blocks on the page for dynamic content. One is a loading image gif which only appears directly after clicking the button. All while the Ajax request is loading we keep that image displayed to let the user know we’re still processing data.

Once the link data comes back we append that into an empty div with the ID #response. Then we would also hide the loading image and reset the submit button to handle more link requests. I notice that TinyURL is generally quick with existing links, but obscure websites may take a few moments to generate a new link and add that into their database before giving a response.

Handling URL Requests

I can’t use a real form element because the PHP script we want to access pulls data from TinyURLs website. Therefore I’ve setup a click event handler which stops the default event on the anchor link and instead calls a custom AJAX function.

$(document).ready(function(){
  $(".submitbtn").on("click", function(e){
    e.preventDefault();
    var longurl = $("#url").val();
    var dataurl = "url="+longurl;
    var resdiv  = $("#response");
		
    $(this).css("display", "none");
    $("#loading").css("display", "block");

The three variables are useful for the Ajax request and response data. I first pull the current link value entered by the user and add this into a dataurl. We need to use that as a request parameter passed into our backend script. Additionally I’ve setup a selector right onto the #response div so we can quickly target this later on.

Before calling the Ajax function we also need to setup the loading gif to display instead of the submit button. It’s a nice bit of user functionality that keeps people from submitting their links twice or three times by accident.

Working with Dynamic Ajax

The largest block of jQuery in this script is used for accessing an XHR Ajax request. I set this into a variable so we could work with any response data or errors from the server. I’m targeting a local script ajax.php which is where we are tying into the TinyURL API.

var xhr = $.ajax({
  type: "POST",
  url: "ajax.php",
  data: dataurl,
  success: function(html){
	if(html == "Error") {
	  resdiv.html("Whoops! Looks like this one didn't work.");
	} else {
	  var newc = 'Presto! → <a href="'+html+'" target="_blank">'+html+'</a>';
	  resdiv.html(newc);
    }
  $("#submitbtn").css("display", "inline-block");
  $("#loading").css("display", "none");
  $("#url").val("");
  },
  error: function(xhr){
	resdiv.html(xhr.statusText);
  $("#submitbtn").css("display", "inline-block");
  $("#loading").css("display", "none");
  }
}); // end ajax call

The two default Ajax responses are on success or failure, and each is tied to a unique function. It’s still possible that we can successfully access the API, but get an error back from TinyURL. This won’t be picked up as an error from the Ajax request so we handle this using an if/else clause inside the first function block.

No matter what response comes back from the server, we want to append that data onto the page. At the end of this function I’ve also hidden the loading image and re-displayed our submit button. Also we clear out the input field so the user can enter another URL quickly.

If we end up with an error response from the Ajax request I’ve just setup a small alert box to share the current text status. This will very rarely ever happen since we will most always have a successful response, as long as jQuery can talk to our PHP script. And since we’re handling errors in the success function it’s unlikely you’ll ever run into this alternate error block.

PHP and the TinyURL API

For this last bit we should take a look at my ajax.php source file. It’s only about 15-20 lines long but the code is super important for making the connection into TinyURL.

The first couple lines are setting up variables we need to access. $url contains the long URL entered by the user which we pass into PHP from jQuery. $fp makes a file request using fopen() from an alternate web server. This is the simplest way we can access a 3rd party script on another website and scrape the data for us to work with.

<?php
$url = $_POST['url'];
$fp = fopen( 'http://tinyurl.com/api-create.php?url='.$url, 'r');

if($fp) {
  $tinyurl = fgets($fp);

  if($tinyurl && !empty($tinyurl)) {
    // if we get a response set the new short URL variable
    $returnurl = $tinyurl; 
    fclose($fp);
  }
}
	
echo $returnurl;
?>

The if logic statement checks if we have a successful connection into the script. The fgets() method will pull all the data from our file pointer and save this into a new variable $tinyurl. We check if it’s not empty and if that looks good then we set this new shortened URL as our return value and echo it onto the page.

Ajax can then use this returned data as our HTML response and apply it onto the page. I’m using an anchor link when we apply this new short URL so it’s easier to copy the link and test it out in your browser. But for such a small script this is one fascinating idea.

TinyURL Links Generator with Ajax - preview

Wrapping Up

This tutorial is a lot of fun for new web developers interested in API programming. It can be daunting to start out with a large network such as Facebook or Twitter. But since TinyURL doesn’t require an API key it’s so much easier to work with. Also the PHP code isn’t so difficult that you’re lost in the mess without any online resources.

If you have the ability to host this script on your own website feel free to do so. It’s never been easier to share open source code and work with partners on different projects around the world. It’s my hope that this tutorial will educate developers and also provide a custom resource for Ajax-based TinyURL links generation. If you have any questions or further ideas on the code feel free to share with us in the post discussion area below.

Powered by Shutterstock

About Jake Rocheleau

Jake is a digital researcher and writer on many popular design magazines. He frequently writes on topics including web design, user experience, mobile apps, and project management. You can find him all throughout Google and tweeting @jakerocheleau. Connect with Jake on google+

It's pretty quiet on this post. Why not share your thoughts?

Leave a Comment

Your email address will not be published. Required fields are marked *