'Trying to scan a QR Code then call an API

I am trying to create a mobile app where the user will scan a unique QR code, the program should then perform a check to make sure that the correct QR code was scanned (instead of just a random QR code) and if the correct code QR was scanned the API should be called. I found a javascript qr scanner that works on mobile phones from https://www.sitepoint.com/create-qr-code-reader-mobile-website/. This all works perfectly in that it accesses the devices camera and scans a QR code but I am struggling on how to perform a check that the correct QR code was scanned. For the sake of testing the "correct" QR code just translates to a string "hello".

I have tried using alert(res) to find the point where the QR is decoded. When I try to use an if statement to compare the decoded QR to a variable equivalent to "hello", the QR scanner just stops working.

The full code can be seen at https://www.sitepoint.com/create-qr-code-reader-mobile-website/

Here is the part which decodes the QR image.

function openQRCamera(node) {
  var reader = new FileReader();
  reader.onload = function() {
    node.value = "";
    qrcode.callback = function(res) {
      if(res instanceof Error) {
        alert("No QR code found. Please make sure the QR code is within the camera's frame and try again.");
      } else {
        node.parentNode.previousElementSibling.value = res;      }
        alert(res)
    };
    qrcode.decode(reader.result);
  };
  reader.readAsDataURL(node.files[0]);
}

The part where it says alert(res) is where i beleive the QR image is decoded, I have tried various if statments but can not get it to work can anyone help.



Solution 1:[1]

Using the above link from sitepoint.com and following the tutorial I didn't run into any issues with the returned response. Try checking if it works like this:

function openQRCamera(node) {
  var reader = new FileReader();
  reader.onload = function() {
    node.value = "";
    qrcode.callback = function(res) {
      if(res instanceof Error) {
        alert("Failed to scan QR code.");
      } else {
        console.log("Scanned new code: " + res.trim());
        if (res.trim() === "hello") {
          alert("Correct code!");
        } else {
          alert("Incorrect code!");
        }
      }
    };
    qrcode.decode(reader.result);
  };
  reader.readAsDataURL(node.files[0]);
}

function showQRIntro() {
  return confirm("Please scan the code");
}

I used this image as an example of a correct code and this image as an example of an incorrect one.

Hope that clears things up, good luck :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bbutkovic