Build a Quick and Easy QR Code Generator with Ajax and Goo.gl

Google has a great URL shortening service at, http://goo.gl. Any URLs you shorten while logged in will also be recorded in your history. On top of the service Google also provides an API accessible at http://www.googleapis.com/urlshortener/v1/url.

Additionally, if you add “.qr” to the end of any short URLs generated by the service the result will be a QR code image that, when scanned, will take you to the URL.

To get familiar with the API I decided to build a JavaScript function that could shorten URLs via Ajax calls to the service. Additionally I wanted to generate the QR codes for the URLs and dynamically render them on the page.

I counted on jQuery to implement my Ajax calls and manipulate my pages to render the resulting images. I was able to complete the task in fifteen lines of JavaScript code.

I’ve included the complete HTML and JavaScript below and you may also view the working QR generator online.

The Goo.gl shortener is extremely useful and simple to use. I’m actively trying to think of more applications where I can utilize it.

Question: What uses can you think of for this shortener?


<!DOCTYPE html >
< html lang= "en">
< head>
< meta http-equiv="Content-Type" content="application/json" />
< title> URL Shortener </title >
< script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></ script >
</head>
< body>
< label for= "longUrl"> Long URL</ label >
< input type= "text" id ="longUrl" />
< button id= "btnShorten"> Shorten</ button >
< section>
< ul id= "shortenedUrls"></ul>
</section>
< script>
// initialize
$( init);

// the initialization function defined
function init() {
$( ‘#btnShorten’).click(shortenUrl);
}

// function shortens url and displays result
function shortenUrl() {
// declare variable
var longUrl = $ (‘#longUrl’). val();
$. ajax({
type: “POST”,
url: “https://www.googleapis.com/urlshortener/v1/url” ,
data: ‘{ “longUrl”: “‘ + longUrl + ‘” }’,
contentType: “application/json; charset=utf-8” ,
dataType: “json”,
}).done (function( msg ) {
shortUrl = msg.id;
$( ‘#shortenedUrls’).append(“<li><a href='” + shortUrl + “‘><img src='” + shortUrl + “.qr’/></a></li>”);
}).fail (function (jqXHR , textStatus, errorThrown) {
alert( “Request failed: ” + errorThrown );
});
}
</script>
</body>
</html>

Leave a Reply