mercredi 7 novembre 2012

jQuery and JavaScript: generate and read a QR Code

Hello everybody!
today we are going to see something really interesting that someone in the past asked me via email.
We are going to generate a QR code using a jQuery plug in and then we are going to use a JavaScript library to read the very same QR code.
What do you think, is it interesting enough?

Generate the QR code
In order to generate the QR code we just need to use a small jQuery plug in called jquery.qrcode.js which is a "jQuery plugin for a pure browser qrcode generation".
As explained in the plug in page, the creation of a QR code is pretty straightforward:
1) include the plugin:

<script type="text/javascript" src="jquery.qrcode.min.js"></script>
2) Insert the target container:
<div id="qrcode"></div>
3) Generate the QR code:
jquery('#qrcode').qrcode("the web thought");
The plug in can render the QR code in canvas or in table.

Read a QR code
Reading a QR code is different stuff: we can use jsqrcode.js. The idea here is similar to the creation.
We need to include the libraries as explained in the above Github page (see Readme file).
To decode a QR code, we can use the following two lines of code:
qrcode.callback = function(data) { alert(data); };
qrcode.decode("qrcodeTest.png");
where the qrcodeTest.png is our QR code image that stays in the same folder as the web page containing the above decoding snippet.
The callback function gets from the data parameter the value resulting from the QR code decode process.
Just to make things more clear, have a look at the following code:
<script src="jquery.js"></script>
<script type="text/javascript" src=" QRCode.js"></script>
<script type="text/javascript">
$(document).ready( function() {
    qrcode.callback = showInfo;
    $("#btnDecode").click(qrCodeDecoder);
  })
 
  function qrCodeDecoder() {
    qrcode.decode("qrcodeTest.png")
  }
 
  function showInfo(data) {
    alert(data);
  }
</script>
</head>
<body>
<div>
<img id="qrcode" src="qrcodeTest.png"/>
</div>
<button id="btnDecode>Decode the QR Code</button>
After including the jQuery and the jsqrcode libraries, we use a button to trigger the call back and the decode of the png file (qrcodeTest.png).

Ok, guys and gals. That's enough for today.
As usual if you need more info, just drop a line in the comment section below.

0 Responses to “jQuery and JavaScript: generate and read a QR Code”

Enregistrer un commentaire

All Rights Reserved Blogging Tips | Blogger Template by Bloggermint