Thursday, September 19, 2013

How to display QR Code dynamically on blogspot using Google Chart Tools

Hi, did you see QR Code on my widget? You should be able to see there, on the right sidebar. Yes, that's dynamic qr code I created using Google Chart Tools and jQuery. It creates QR Code contains current URL of the page. If you like too, I'll show you how I did this little trick. Now you can simply do this on your blog, on any blog. Here's how:

Step 1

Make sure you have jquery installed on your blog. Simply add jquery link on HTML/Javascript widget, or if possible, insert before tag </head> or above </body>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
</script>

Step 2

On your HTML/Javascript widget, or if possible, add this before </body>:
<script>
$(function(){
   var current_url = 'http://' + document.domain + window.location.pathname,
       qrData = encodeURIComponent(current_url),
       gChart = 'https://chart.googleapis.com/chart?chs=150x150&cht=qr&choe=UTF-8&chld=L|1&chl='+qrData;

   $('#qr').html('<img src="'+gChart+'" height="150" width="150" />');
});
</script>
window.location.pathname is the current request uri, same as $_SERVER['REQUEST_URI'] on PHP. And then you need use encodeURIComponent() to make the data URL encoded (just like urlencode() on PHP).

We use element ID to display the QR Code. In this case the element ID is qr. Add the element wherever you want. I did this on my sidebar widget.

Step 3

Add element to display QR image:
<div id="qr"></div>
Save your template. You can see the qr code on your page now.

No comments :

Post a Comment