As we will cover this tutorial with live example to build QR code generator using PHP and Ajax, so the major files for this example is following.
- index.php
- ajax_generate_code.js
- generate_code.php
Step1: Create HTML Form with QR Code Options
First we will create Bootstrap HTML Form with required input to generate QR Code. The first input will be Code Content that's can URL, simple text, contact number, email address etc. The second input Code Level with value as (Best, M, Q, Smallest) to display QR code redundancy to use more space. The third input will be Size that's define the number of pixels to generate QR code.
<div class="container">
<div class="row">
<h2>Example: Build QR Code Generator with PHP and Ajax</h2>
<div class="col-md-3">
<form class="form-horizontal" method="post" id="codeForm" onsubmit="return false">
<div class="form-group">
<label class="control-label">Code Content : </label>
<input class="form-control col-xs-1" id="content" type="text" required="required">
</div>
<div class="form-group">
<label class="control-label">Code Level (ECC) : </label>
<select class="form-control col-xs-10" id="ecc">
<option value="H">H - best</option>
<option value="M">M</option>
<option value="Q">Q</option>
<option value="L">L - smallest</option>
</select>
</div>
<div class="form-group">
<label class="control-label">Size : </label>
<input type="number" min="1" max="10" step="1" class="form-control col-xs-10" id="size" value="5">
</div>
<div class="form-group">
<label class="control-label"></label>
<input type="submit" name="submit" id="submit" class="btn btn-success" value="Generate QR Code">
</div>
</form>
</div>
<div class="col-md-6">
<div class="showQRCode"></div>
</div>
</div>
</div>
Step2: Make Ajax Request To Generate QR Code
In ajax_generate_code.js file, we will make Ajax request to generate_code.php with required Form input values to generate QR code and display it.
$(document).ready(function() {
$("#codeForm").submit(function(){
$.ajax({
url:'generate_code.php',
type:'POST',
data: {formData:$("#content").val(), ecc:$("#ecc").val(), size:$("#size").val()},
success: function(response) {
$(".showQRCode").html(response);
},
});
});
});
Step3: Generate QR Code
In generate_code.php file, we will handle functionality with library PHP QR Code to create QR code image file with QRcode function png() in directory codes using form values and return generated QR code image to display on page.
<?php
if(isset($_POST) && !empty($_POST)) {
include('library/phpqrcode/qrlib.php');
$codesDir = "codes/";
$codeFile = date('d-m-Y-h-i-s').'.png';
$formData = $_POST['formData'];
QRcode::png($formData, $codesDir.$codeFile, $_POST['ecc'], $_POST['size']);
echo '<img class="img-thumbnail" src="'.$codesDir.$codeFile.'" />';
} else {
header('location:./');
}
?>
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]