Categories
PHP

Creating online QR codes with goQR.me API

QR Codes are fashionable little things with many, many uses. I had previously worked on an implementation of QR Codes in a project using the Google Charts API which 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):

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.

<img src="http://api.qrserver.com/v1/create-qr-code/?data=HelloWorld!&size=100x100" />

which results in:

QR Code
QR Code

index.php

<!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:

<?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…

By foxbeefly

PHP / MySQL Developer

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.