October 24, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Build a URL Shortener with jQuery, PHP and MySQL

  • July 28, 2010
  • By Jason Gilmore
  • Send Email »
  • More Articles »

Step 4. Integrate the Ajax

With the PHP script tested, let's add the Ajax enhancement. Of course, you'll need to integrate jQuery, which is easily and efficiently accomplished by referencing it via Google's content distribution network (Google Libraries API).

Beyond including the jQuery library, the following snippet will attach an event handler to the form's submission action. When the form is submitted, the value passed to the form's url form field is retrieved and passed to the shorten.php script using jQuery's $.POST function. Finally, the DIV identified by the response ID will be populated with either an error message or the abbreviated URL depending upon the outcome of the shorten.php script.

<script src="http://www.google.com/jsapi?key=YOUR_GOOGLE_AJAX_API_KEY" type="text/javascript"></script> <script src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("jquery", "1.4.2"); </script> <script type="text/javascript"> $(document).ready(function(){ // Associate an event handler with the form submission action $('#form_url').submit(function(e) { // Retrieve the form's URL field value var url = $('#url').val(); // POST the URL to the shorten.php script $.post( "shorten.php", {url: url}, function(data){ if (data == "FALSE") { $("#response").html("There was a problem shortening your URL"); } else { $("#response").html("Your shortened URL: <a href='" + data + "'>" + data + "</a>"); } }, "text" ); // Prevent the form from actually submitting e.preventDefault(); }); }); </script> 

Step 5. Create the Redirection Script

The redirection script (redirect.php) is responsible for converting the abbreviated URL into its elongated counterpart, in addition to adjusting the row's clicked column upwards. Like the shortener script, this is pretty straightforward: it first verifies that the provided abbreviation exists and if so, it adjusts the click count before redirecting the user. Here's the script:

<?php define("SERVICE", "http://u.wjgilmore.com/"); $db = new mysqli("localhost", "webuser", "test", "shortener"); // If an abbreviation has been provided, process it if (isset($_GET['abbreviation'])) { $abbreviation = $_GET['abbreviation']; $stmt = $db->prepare("SELECT url, clicked FROM urls WHERE abbreviation = ?"); $stmt->bind_param("s", $abbreviation); $stmt->execute(); $stmt->store_result(); // Was the abbreviation found in the database? if ($stmt->num_rows == 1) { $stmt->bind_result($url, $clicked); $stmt->fetch(); $clicked++; // Update the click counter $stmtUpdate = $db->prepare("UPDATE urls SET clicked = ? WHERE abbreviation = ?"); $stmtUpdate->bind_param("ds", $clicked, $abbreviation); $stmtUpdate->execute(); // Redirect user to appropriate URL header('Location: '. $url); } else { echo "This URL does not exist!"; } } ?> 

Because we want the URLs to be as compact as possible, it wouldn't do to include the redirection file name (redirect.php) in the abbreviated URL. To remove the filename, we can use a simple .htaccess file to redirect all strings that don't match a filename or directory found in the website's home directory to redirect.php:

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ redirect.php?abbreviation=$1 [QSA,L] 

Where to From Here?

The URL shortener service is operational! Of course, there's plenty of room for improvement, as I took a number of shortcuts in order to fit the code and discussion into a format suitable for publication here on Developer.com. Grouping configuration information into a single file would be an improvement, and it would certainly be beneficial to refactor much of the functionality into an object-oriented class. Additionally, some additional checks should be implemented to ensure that a duplicate random abbreviation isn't generated, which although highly unlikely is still possible.

Just for kicks I'll continue working on the code as time allows. You can monitor the project and download the code at github.com/wjgilmore/yoyo.

Conclusion

Building a link-shortening service is a fun and educational way to get acquainted with the intricacies of creating a functional, Ajax-enhanced website. Try experimenting with the code and adding your own features! And as always, if you do anything cool with it, let us know in the comments!

About the Author

Jason Gilmore is founder of WJGilmore.com. He also is the author of several popular books, including "Easy PHP Websites with the Zend Framework", "Easy PayPal with PHP", and "Beginning PHP and MySQL, Third Edition".


Tags: PHP, MySQL, jQuery



Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel