Dynamically Generate vCard QR Code using PHP, JavaScript, and Ajax

A Virtual Contact Card aka vCard is used to share contact details on mobile devices. With vCard one can save details like name, contact numbers, website, email, company, etc. to their mobile device automatically. You don’t need to enter all these details before saving a contact.

In this tutorial, we’ll generate a vCard QR code. Once this QR code is scanned, all the details pop up on the mobile device. Users then either save these details or share them from their mobile devices.

We’ll also allow you to save the generated QR code into PDF. This PDF can be shared with anyone via electronic devices.

To achieve our goal, I’m going to use the below libraries.

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

Create HTML Form

First, it needs to generate a QR code that contains information about a user. Let’s create the HTML form to enter the details and submit it to the server-side for the rest process. Basically, we send form data via Ajax, generate a QR code, and send it back to the client.

<form method="post" id="frmQRCode" onsubmit="generateQRCode();return false;">
    <p>
        <input type="text" name="fullname" placeholder="Full Name" required />
    </p>
    <p>
        <input type="text" name="designation" placeholder="Designation" required />
    </p>
    <p>
        <input type="text" name="company" placeholder="Company" required />
    </p>
    <p>
        <input type="text" name="workcontact" placeholder="Office Contact Number" required />
    </p>
    <p>
        <input type="text" name="homecontact" placeholder="Home Contact Number" required />
    </p>
    <p>
        <input type="text" name="mobile" placeholder="Mobile" required />
    </p>
    <p>
        <input type="email" name="email" placeholder="Email" required />
    </p>
    <p>
        <input type="text" name="website" placeholder="Website" required />
    </p>
    <p>
        <input type="text" name="address" placeholder="Address" 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, I have added a few fields to enter the user’s information. Apart from it, I included JS files of html2canvas and jspdf via CDN. These files will help to create a PDF out of HTML. Also, I included a custom.js file where we’ll write a logic of an Ajax request and create the PDF.

JavaScript Code (custom.js)

Let’s create a custom.js file in your project directory. After this, write the below code into it.

function generateQRCode() {
    var form_data = new FormData(document.getElementById("frmQRCode"));
 
    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
    });
}

Two methods are defined in the above JavaScript file.

  • generateQRCode() : This method collects the form data, sends it to the server-side script, receives a response, and appends it to HTML.
  • save_qrcode_to_pdf() : This function takes the HTML written inside a div having an id ‘content’. And generate a PDF with this HTML.

Generate a vCard QR Code (generate-qrcode.php)

As I mentioned before, we’ll use the GitHub library which allows us to create a QR code in PHP. Install the library using the below command:

composer require chillerlan/php-qrcode

Upon package installation, create a generate-qrcode.php file and add the following code to it.

<?php
require_once "vendor/autoload.php";
 
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
 
extract($_POST);

// create VCARD
$vcard = "BEGIN:VCARD\r\n";

if ( !empty($fullname) ) {
    $fullname = implode(";", explode(" ", $fullname));
    $vcard .= "N:$fullname;\r\n";
}

if ( !empty($designation) ) {
    $vcard .= "TITLE:$designation\r\n";
}

if ( !empty($company) ) {
    $vcard .= "ORG:$company\r\n";
}

if ( !empty($workcontact) ) {
    $vcard .= "TEL;TYPE=work,VOICE:$workcontact\r\n";
}

if ( !empty($homecontact) ) {
    $vcard .= "TEL;TYPE=home,VOICE:$homecontact\r\n";
}

if ( !empty($mobile) ) {
    $vcard .= "TEL;TYPE=mobile:$mobile\r\n";
}

if ( !empty($email) ) {
    $vcard .= "EMAIL:$email\r\n";
}

if ( !empty($website) ) {
    $vcard .= "URL:$website\r\n";
}

if ( !empty($address) ) {
    $vcard .= "ADR;TYPE=WORK,PREF:;;$address\r\n";
}

$vcard .= "VERSION:3.0\r\n";
$vcard .= "END:VCARD";

$qr_image = (new QRCode)->render($vcard);
echo json_encode(array('code' => 'success', 'content' => '<img src="'. $qr_image .'" alt="QR Code" />'));
die;

We’re taking form data and building a string out of it following vCard parameters. To generate a vCard you have to build a string in a certain format. Each detail has its own parameter. For example, to create a name your string will be N:John;Doe;

Similarly, other info like email, address, and website has its own parameters. Study the above code and you’ll familiarize yourself with vCard static parameters.

Now, fill up the form, submit it and you will get the QR code printed below the form. Scan the QR code from the mobile devices, you should get all the information pop up on your mobile. You can create a new contact with these details or share it with your contact list.

Related Articles

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

Leave a Reply

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