Dynamically Generate QR Code using PHP, JavaScript, and Ajax

You may want to generate a QR code for many reasons. The QR codes are easy to share with people. As I want to show you how to programmatically create the QR code, I am taking a scenario where one needs to scan the QR code to see the user’s information. I’ll consider a few details like full name, email, and pictures which will be displayed on scanning a QR code. You can add more details as per your requirement.

To build this flow the below steps will be followed.

  • Create an HTML form to enter the full name, email, and picture.
  • On form submission, the Ajax request will be sent to the server side.
  • Generate a QR code on the server side and store details in the database.
  • Print the QR code on the webpage.
  • Optionally give the option to download the QR code into a PDF.
  • On a scan, one will receive an URL where they can see the information of a user.

I’ll use a few libraries to achieve this task.

  • chillerlan/php-qrcode : This library is used to generate a QR code in PHP.
  • html2canvas and jspdf : These libraries are used to generate a PDF containing a QR code.

Having said that, let’s start with dynamically generating a QR code with PHP.

Database Configuration

To show the information after scanning a QR code, we need a database to store the details of a user against the unique id. This unique id will be appended on the URL(appear after scan). Using this id, we’ll fetch details from the database.

Create the users table by running the below SQL.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `qrcode_id` varchar(255) DEFAULT NULL,
  `fullname` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `picture` varchar(255) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Next comes a code to interact with the database. I’ll write methods to insert and fetch the user details. This code will go into the class-db.php file.

<?php
class DB {
    private $dbHost     = "DB_HOST";
    private $dbUsername = "DB_USERNAME";
    private $dbPassword = "DB_PASSWORD";
    private $dbName     = "DB_NAME";
 
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
 
    public function get_user($id) {
        $query = sprintf("SELECT * FROM users WHERE qrcode_id = '%s'", $this->db->real_escape_string($id));
        $sql = $this->db->query($query);
        return $sql->fetch_assoc();
    }
  
    public function insert_user($arr_data = array()) {
        $qrcode_id = $this->db->real_escape_string($arr_data['qrcode_id']);
        $name = $this->db->real_escape_string($arr_data['fullname']);
        $email = $this->db->real_escape_string($arr_data['email']);
        $picture = $this->db->real_escape_string($arr_data['picture']);
  
        $sql = sprintf("INSERT INTO users(qrcode_id, fullname, email, picture) VALUES('%s', '%s', '%s', '%s')", $qrcode_id, $name, $email, $picture);
        $this->db->query($sql);
    }
}

Create HTML Form

In the HTML file, let’s create a form to enter the details. I am going to include libraries – html2canvas and jspdf to this HTML file. For the sake of a tutorial, I am adding them via CDN.

<form method="post" enctype="multipart/form-data" id="frmQRCode" onsubmit="generateQRCode();return false;">
    <p>
        <input type="text" name="fullname" placeholder="Full Name" required />
    </p>
    <p>
        <input type="email" name="email" placeholder="Email" required />
    </p>
    <p>
        <input type="file" name="picture" id="picture" required />
    </p>
    <input type="submit" name="submit" value="Submit" />
</form>
<!-- QR Code will appear here -->
<div class="qrcode-image" style="display:none;">
    <div id="content"></div>
    <button onclick="save_qrcode_to_pdf();">Save to PDF</button>
</div>

<script src="custom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

Here, you may have noticed 2 methods – generateQRCode() and save_qrcode_to_pdf(). These methods are self-explanatory. I’ll define these functions in the custom.js file which is already included in the above HTML.

JavaScript Code (custom.js)

With the help of JavaScript, we collect the form data, send data to the server-side script via Ajax and print the response in HTML. A QR code will be appended inside the div having an id ‘content’.

To create a PDF, I’ll get the HTML of this div(having a QR code), build the PDF, and send it to the browser.

function generateQRCode() {
    var form_data = new FormData(document.getElementById("frmQRCode"));

    picture = document.getElementById('picture').files[0];
    form_data.append('picture', picture);

    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "generate-qrcode.php", true);
    xhttp.onload = function(event) {
        if (xhttp.status == 200) {
            if('success' == JSON.parse(this.response).code) {
                document.querySelector('#content').innerHTML = JSON.parse(this.response).content;
                document.querySelector(".qrcode-image").style.display = "block";
            } else {
                alert(JSON.parse(this.response).content);
            }
        } else {
            alert("Error " + xhttp.status + " occurred when trying to upload your documents.");
        }
    }

    xhttp.send(form_data);
}

function save_qrcode_to_pdf() {
    window.jsPDF = window.jspdf.jsPDF;

    var doc = new jsPDF();
        
    // Source HTMLElement or a string containing HTML.
    var elementHTML = document.querySelector("#content");

    doc.html(elementHTML, {
        callback: function(doc) {
            // Save the PDF
            doc.save('qrcode.pdf');
        },
        x: 15,
        y: 15,
        width: 170, //target width in the PDF document
        windowWidth: 650 //window width in CSS pixels
    });
}

In the above code, I am posting data to the generate-qrcode.php file. This file will store details in the database and generate a QR code.

Generate a QR Code (generate-qrcode.php)

Before writing a code to this file, install the QR code generator library with the following Composer command.

composer require chillerlan/php-qrcode

You should include the environment of the package and database class file in the generate-qrcode.php file.

<?php
require_once "vendor/autoload.php";
require_once "class-db.php";

use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;

$qrcode_id = time().uniqid();

if ( !file_exists('uploads') ) {
    mkdir('uploads', 0755);
}

$filename = time().$_FILES['picture']['name'];
move_uploaded_file($_FILES['picture']['tmp_name'], 'uploads/'.$filename);

$data = array(
    'qrcode_id' => $qrcode_id,
    'fullname' => $_POST['fullname'],
    'email' => $_POST['email'],
    'picture' => $filename,
);
$db = new DB();
$db->insert_user($data);

$url = "SITE_URL/reader.php?id=".$qrcode_id;
$qr_image = (new QRCode)->render($url);
echo json_encode(array('code' => 'success', 'content' => '<img src="'. $qr_image .'" alt="QR Code" />'));
die;

From this file, I am returning a JSON response which will be handled by the JavaScript code. It’ll print the QR code on the webpage.

Upon scanning the QR code, the URL will appear as something like SITE_URL/reader.php?id=some_unique_id .

When this URL hits the browser, we have to display the information related to this unique id.

Print Information (reader.php)

Finally, print the user’s information with the help of the following code.

<?php
require_once "class-db.php";

$id = $_GET['id'];

$db = new DB();
$data = $db->get_user($id);
?>

<div class="info">
    <img src="<?php echo "SITE_URL/uploads/".$data['picture']; ?>" width="200" alt="picture">
    <p>Fullname: <?php echo $data['fullname']; ?></p>
    <p>Email: <?php echo $data['email']; ?></p>
</div>

That’s it! You may now test the flow. It should allow you to generate a QR code and print details upon scanning it. You may also like to read our article – generate vCard QR code using PHP.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

2 thoughts on “Dynamically Generate QR Code using PHP, JavaScript, and Ajax

  1. I want to ask is there any code that we can generate the QR code with just unique id, and fill up the data later after the QR code have been generated by scanning the QR code.

    1. Of course, you can do it. Here, I am inserting details while generating a QR code. You can skip this database insertion part.

Leave a Reply

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