QR Codes are fashionable little things!
I had previously worked on an implementation of QR Codes in a project using the Google Charts API — I see that is now deprecated…
Fortunately there are any number of API’s available: this is a simple implementation of a QR Code generator using the free goQR.me API. I added a bit of jQuery to keep things interesting, but the key to the following code is simply in passing a few parameters via the URL like so (paste in your browser to test):
1 |
http://api.qrserver.com/v1/create-qr-code/?data=HelloWorld!&size=100x100 |
Displaying the QR code in a webpage is then as simple as using the above as the value of the src
attribute in an image tag.
1 |
<img src="http://api.qrserver.com/v1/create-qr-code/?data=HelloWorld!&size=100x100" /> |
which results in:
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/javascript" language="javascript" src="jquery-1.11.0.js"></script> </head> <body> <h2>QR Codes demo</h2> <p><label class="for" for="encode_this">Encode this:</label><input name="encode_this" id="encode_this" /><button id="get_code">Get QR Code</button></p> <div id="imageContainer">Nothing yet...</div> <script type="text/javascript"> $(document).ready(function() { // getQRcode(); $('#get_code').click(function(){ var theQuery = $('#encode_this').val(); if(theQuery.length>0) { $.ajax({ type: "POST", url: "AJAXqr.php", cache: false, data: { get_qr: theQuery }, error: function(msg) { alert(msg); }, success: function(text) { $("#imageContainer").html(text); } }) } else { alert('You have entered nothing'); } return false; }); }); </script> </body> </html> |
AJAXqr.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php session_start(); define("QRSERVER", "http://api.qrserver.com/"); function get_qr($to_encode) { $size = 100; $encode_d = urlencode($to_encode); return '<img src="'.QRSERVER.'v1/create-qr-code/?data='.$encode_d.'&size='.$size.'x'.$size.'" alt="'.$to_encode.'" title="'.$to_encode.'" />'; } if($_POST['get_qr']) { echo get_qr($_POST['get_qr']); } ?> |
See demo here…