How to compare database value with javascript value.? - javascript

I want to compare lastResult value with database qr code value, if both match redirect to a page else show error. My database is phpmyadmin. I'm using laravel 7 but doing this with html and javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<title>QR Code Scanner</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/html5-qrcode"></script>
</head>
<body>
<div id="qr-reader" style="width:500px"></div><br>
<div id="qr-reader-results" style="padding:10px"></div>
<script>
var resultContainer = document.getElementById('qr-reader-results');
var lastResult, result, countResults = 0;
function onScanSuccess(decodedText, decodedResult) {
if (decodedText !== lastResult) {
++countResults;
lastResult = decodedText;
// Handle on success condition with the decoded message.
// console.log (`Scan result ${decodedText}`, decodedResult);
document.getElementById("qr-reader-results").innerHTML= lastResult;
}
}
var html5QrcodeScanner = new Html5QrcodeScanner(
"qr-reader", { fps: 10, qrbox: 250 });
html5QrcodeScanner.render(onScanSuccess);
</script>
</body>
</html>

Thanks M. Eriksson. I found the solution. It is done without ajax request.
function onScanSuccess(decodedText, decodedResult) {
if (decodedText !== lastResult) {
++countResults;
lastResult = decodedText;
// Handle on success condition with the decoded message.
// console.log (`Scan result ${decodedText}`, decodedResult);
// document.getElementById("qr-reader-results").innerHTML= lastResult;
if(lastResult == "{{ auth()->user()->qrcode }}"){
alert("matched");
location.href="/home";
}else{
alert("unmatched");
}
}
}

Related

clearInterval inside of socket getStates function

I try to use a modified socket.io adaption for iobroker (smart home broker) with a setInterval function for showing every second the time ago of the last received timestamp of
It works so far, till the second updated timestamp comes... It seems clearInterval did not stop the interval and the timer is running twice with the old and new timestamp.
How and where do i have to clearInterval correctly?
Updated:
If onUpdate activates the servConn.getStates([stromvIDts]function and received a new timestamp of stromvIDts, the interval should run and show the time ago (every second updated). If (after around 2-3 min) a new value is there, the interval should stop and a new one starting and showing every second the past time of the new timestamp, e.g. "some seconds ago"... 2 Minutes ago ...)
My code:
servConn.namespace = 'mobile.0';
servConn._useStorage = false;
var stromv = 'hm-rpc.1.MEQ123456.1.POWER';
var subscriptions = [stromv];
var states = [];
servConn.init({
name: 'mobile.0',
connLink: 'http://IP:8082',
socketSession: ''
}, {
onConnChange: function(isConnected) {
if (isConnected) {
console.log('connected');
} else {
console.log('disconnected');
}
},
onUpdate: function(id, state) {
setTimeout(function() {
states[id] = state;
let stromvID = states[stromv].val;
let stromvIDts = states[stromv].ts;
//Get States of subsribed states if changed
servConn.getStates([stromvID], (error, states) => {
document.getElementById("stromvAktuell").innerHTML = stromvID + " W/h";
});
servConn.getStates([stromvIDts], (error, states) => {
function stopInterval() {
clearInterval(timerId);
};
timerId = setInterval(function() {
updateTimeAgo();
}, 1000);
function updateTimeAgo() {
let duration = moment(stromvIDts).fromNow();
console.log(duration);
document.getElementById("stromvTs").innerHTML = duration;
};
});
}, 0);
},
onError: function(err) {
window.alert(_('Cannot execute %s for %s, because of insufficient permissions', err.command, err.arg), _('Insufficient permissions'), 'alert', 600);
}
}, false, false);
servConn._socket.emit('subscribe', subscriptions);
<!DOCTYPE html>
<html lang="de">
<head>
<link rel="icon" href="data:,">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
<title>TEST</title>
<script src="http://IP:8082/socket.io/socket.io.js"></script>
<script src="../tmp/conn.js"></script>
<script src="moment-with-locales.js"></script>
<script>
moment.locale('de')
</script>
</head>
<body>
<div>
Value: <b id="stromvAktuell">unknown</b>
<br> Last update: <b id="stromvTs">unknown</b>
<br>
</div>
</body>
Instead of creating new intervals and clearing the old one, just start one interval and update the value every time onUpdate runs:
If you want the time since the last update, you can use Date.now().
servConn.namespace = 'mobile.0';
servConn._useStorage = false;
var stromv = 'hm-rpc.1.MEQ123456.1.POWER';
var subscriptions = [stromv];
var states = [];
let lastTimestamp = -1;
let duration = -1;
timerId = setInterval(function() {
updateTimeAgo();
}, 1000);
function updateTimeAgo() {
console.log(Date.now() - lastTimeStamp);
document.getElementById("stromvTs").innerHTML = Integer((Date.now() - lastTimeStamp)/1000);
};
servConn.init({
name: 'mobile.0',
connLink: 'http://IP:8082',
socketSession: ''
}, {
onConnChange: function(isConnected) {
if (isConnected) {
console.log('connected');
lastTimestamp = Date.now();
} else {
console.log('disconnected');
}
},
onUpdate: function(id, state) {
setTimeout(function() {
states[id] = state;
let stromvID = states[stromv].val;
let stromvIDts = states[stromv].ts;
//Get States of subsribed states if changed
servConn.getStates([stromvID], (error, states) => {
document.getElementById("stromvAktuell").innerHTML = stromvID + " W/h";
});
lastTimeStamp = Date.now();
}, 0);
},
onError: function(err) {
window.alert(_('Cannot execute %s for %s, because of insufficient permissions', err.command, err.arg), _('Insufficient permissions'), 'alert', 600);
}
}, false, false);
servConn._socket.emit('subscribe', subscriptions);
<!DOCTYPE html>
<html lang="de">
<head>
<link rel="icon" href="data:,">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
<title>TEST</title>
<script src="http://IP:8082/socket.io/socket.io.js"></script>
<script src="../tmp/conn.js"></script>
<script src="moment-with-locales.js"></script>
<script>
moment.locale('de')
</script>
</head>
<body>
<div>
Value: <b id="stromvAktuell">unknown</b>
<br> Last update: <b id="stromvTs">unknown</b>
<br>
</div>
</body>

I am not sure I can access the second html file using one js file, html element is showing as null when it is a button

I have 2 html files connected to one js file. When I try to access a html element in the second html file using js it doesn't work saying that is is null. I did
let elementname = document.getElementById("element") for a element in the second html page then
console.log(elementname) and it says it is null. When I do it for a element in the first html page it says HTMLButtonElement {}
Here is the html for the first Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Not Quuuuiiiizzzz</h1>
<h2>Join a quiz</h2>
<!--Buttons -->
<div style="text-align: center;">
<button id="btnforquiz1" onclick="gotoquiz()"></button>
<button id="btnforquiz2" onclick="gotoquiz1()"></button>
<button id="btnforquiz3" onclick="gotoquiz2()"></button>
</div>
<h2 id="h2">Create a Quuuuiiiizzzz</h2>
<script src="script.js"></script>
</body>
</html>
For the second page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="quizLoad()">
<h1 id="question">Hello</h1>
<button id="answer1"></button>
<button id="answer2"></button>
<button id="answer3"></button>
<button id="answer4"></button>
<script src="script.js"></script>
</body>
</html>
And Finally for the js file :
//setting global variables
let btn1 = document.getElementById("btnforquiz1") //getting button with id of btnforquiz1 repeat below
correct = 0
let btn2 = document.getElementById("btnforquiz2")
let btn3 = document.getElementById("btnforquiz3")
let question = document.getElementById("question")
let answer1 = document.getElementById("answer1")
let answer2 = document.getElementById("answer2")
let answer3 = document.getElementById("answer3")
let answer4 = document.getElementById("answer4")
quizNameRel = -1;
cosnole.log(question)
console.log(answer1)
//Quiz Data
Quiz_1 = {
"What is the capital of buffalo":["Idk", "Yes", "No",0],
"What is the smell of poop": ["Stinky"]
};
Quiz_2 = [
"What is wrong with you"
];
Quiz_3 = [
"What is wrong with you #2"
]
let quiz = {
name: ["History Test", "Math Practice", "ELA Practice"],
mappingtoans: [0,1,2],
QA: [Quiz_1, Quiz_2, Quiz_3]
}
//quiz data
//when body loades run showQuizzs function
document.body.onload = showQuizzs()
function showQuizzs() {
//loops throo the vals seeting the text for the btns
for (let i = 0; i < quiz.name.length; i++) {
btn1.textContent = quiz.name[i-2]
btn2.textContent = quiz.name[i-1]
btn3.textContent = quiz.name[i]
}
}
//leads to the showQuizzs
function gotoquiz() {
location.href = "quiz.html"
quizNameRel = quiz.name[0]//I was trying to create a relation so we could knoe which quiz they wnt to do
startQuiz()
}
function gotoquiz1() {
location.href = "quiz.html"
quizNameRel = quiz.name[1]
startQuiz()
}
function gotoquiz2() {
location.href = "quiz.html";
quizNameRel = quiz.name[2];
startQuiz();
}
function answerselect(elements){
whichone = Number(elements.id.slice(-2,-1))
if(Quiz_1[whichone]==Quiz_1[-1]){
correct+=1;
NextQuestion();
}else{
wrong+=1;
}
}
//gets the keys and puts it into an array
function getkeys(dictionary){
tempdict = [];
for(i in dictionary){
tempdict.push(i);
}
return tempdict;
}
function setQuestion() {
let tempdict = getkeys(Quiz_1)
console.log(tempdict, getkeys(Quiz_1));
//question.innerHTML = tempdict;
}
// startQuiz
function startQuiz() {
switch (quizNameRel){
case quiz.name[0]:
//case here
setQuestion()
break
case quiz.name[1]:
//case here
break
case quiz.name[2]:
//case here
break
}
}
//TO DO:
// Set the question
// Set the answer
// Check if correct button
This is happening because at a time you have rendered only one html file. For example if you render index1.html(first file) then your js will look for rendered element from first file only but here index2.html(second file) is not rendered so your js script is unable to find elements of that file that's the reason it shows null.
If you try to render now index2.html rather than index1.html then you will find now elements from index2.html are detected by js script but elements from index1.html are null now.

Mask original e-mail on registration page using Javascript

I need to setup a page that allows users to register using their e-mail but as a requirement the e-mail shouldn't be "visible" for human eyes, I guess there's got to be a better way to do it, but so far I came up with this option using JQuery:
I created a fake control that handles the masking and captures the text so that it can be assigned to a hidden field (so that the previously working code will keep working without changes).
var emailControl = $("#eMail");
var firstHalf = "";
var secondHalf = "";
var fullMail = "";
emailControl.keyup(function(e){
var control = e.currentTarget;
var currentText = $(control).val();
if (currentText.length == 0){
fullMail = '';
firstHalf = '';
secondHalf = '';
$(control).attr('type', 'password');
}
else{
var components = currentText.split("#");
var hiddenPart = "•".repeat(components[0].length);
detectChanges(currentText);
if (components.length == 2) {
secondHalf = '#' + components[1];
}
$(control).attr('type', 'text');
$(control).val(hiddenPart + secondHalf);
fullMail = firstHalf + secondHalf;
}
});
function detectChanges(originalText) {
var position = originalText.indexOf('#');
if (position == -1) {
position = originalText.length;
}
for (var i = 0; i < position; i++){
if (originalText[i] != "•"){
firstHalf = firstHalf.substring(0, i) + originalText[i] + firstHalf.substring(i+1);
}
}
}
I did manage to get it working here: https://codepen.io/icampana/pen/KbegKE
You could give the input tag type of password: type="password".
It may cause some janky things to happen with autofill.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form>
email: <input type="password" name="email">
</form>
</body>
</html>
You could also do something similar with CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
input {
-webkit-text-security: circle;
}
</style>
</head>
<body>
<form>
email: <input name="email">
</form>
</body>
</html>

Google maps not showing in html

Apologies, I am really new to this - I am following the google tutorials however I am unable to get the map to show in the html. I know the javascript is executing as I can see some manual console logs I put through the script. I also know the location is taken from the user.
I have 2 separate files, googlemaps.js and home.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Title</title>
<script src="{% static 'js/googlemaps.js' %}"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA9etM9rqnYas63ypURAkvEFn_W_sU0NM4&callback=initMap">
</script>
</head>
<body>
<div id="map">
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</div>
</body>
</html>
And in the js file I have :
var curLat = null; //user location
var curLon = null;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
window.alert("no location");
}
}
function showPosition(position) {
curLat = position.coords.latitude;
curLon = position.coords.longitude;
}
function initMap(){
getLocation() //finds out user location to fomat the map
if (curLat == null){
curLat = 42.3601; //if the user location cannot be found, set default ones
curLon = -71.0589; // of boston
console.log("random locations");
}
var options = {
zoom:10,
center:{lat:curLat, lng:curLon}
}
var map = new google.maps.Map(document.getElementById("map"),options);
}
If possible, could you please point me to what I am doing wrong in the HTML? Thank you
You have two errors:
1- You have to use if(curLat == null) note that double equal
2- The style property for map is not set correctly.
This two files in same folder work for me:
index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Title</title>
<script src="googlemaps.js"></script>
</head>
<body>
<div id="map" style="height: 400px; width: 100%;">
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA9etM9rqnYas63ypURAkvEFn_W_sU0NM4&callback=initMap">
</script>
</body>
</html>
And googlemaps.js:
var curLat = null; //user location
var curLon = null;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
window.alert("no location");
}
}
function showPosition(position) {
curLat = position.coords.latitude;
curLon = position.coords.longitude;
}
function initMap(){
getLocation() //finds out user location to fomat the map
if (curLat == null){
curLat = 42.3601; //if the user location cannot be found, set default ones
curLon = -71.0589; // of boston
console.log("random locations");
}
var options = {
zoom:10,
center:{lat:curLat, lng:curLon}
}
var map = new google.maps.Map(document.getElementById("map"),options);
}
Regards.
There is a few things wrong, firstly you are using which is usually used for templating systems such as twig. To include your js file all you need is
After that where it says if(curLat = null) you are setting the variable to null. I would use if(curLat == null || curLon == null)

Convert a HTML Collection to Javascript Array?

I am a newbie, trying to learn w3c-dom, html-dom, just went through this DOM-Introduction
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
<body>
<script type="text/javascript">
var getByTag = function(selector) {
// FIXME: Do more conditions -- Come Up with more non-verbose regex condition
return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
}
var isHTMLCollection = function(data) {
return data.toString() === '[object HTMLCollection]';
}
var toArray = function(c) {
return Array.prototype.slice.call(c);
}
var getAllPs = getByTag('p');
console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
console.log(Array.isArray(getAllPs), 'isArray-1');
console.log(getAllPs, 'getAllPs');
var _arrayLike = toArray(getAllPs);
console.log(Array.isArray(_arrayLike), 'isArray-2');
console.log(_arrayLike.length, 'Array.length');
</script>
<p id="p1">
First Para
</p>
<p id="p2">
Second Para
</p>
</body>
</html>
While logging this on console, i got just an empty array, when i tried to convert the HTMLCollection to Array.
Note: Tried using for-loop also.
Attached the console output,
Yes, adding
document.addEventListener('DOMContentLoaded', function() { //rest of the code });
fixes the issue
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var getByTag = function(selector) {
// FIXME: Do more conditions -- Come Up with more non-verbose regex condition
return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
}
var isHTMLCollection = function(data) {
return data.toString() === '[object HTMLCollection]';
}
var toArray = function(c) {
return Array.prototype.slice.call(c);
}
var getAllPs = getByTag('p');
console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
console.log(Array.isArray(getAllPs), 'isArray-1');
console.log(getAllPs, 'getAllPs');
var _arrayLike = toArray(getAllPs);
console.log(Array.isArray(_arrayLike), 'isArray-2');
console.log(_arrayLike.length, 'Array.length');
});
</script>
<p id="p1">
First Para
</p>
<p id="p2">
Second Para
</p>
</body>
</html>
Note: Problem with chrome console is, array values are evaluated on asynchronously.
Thanks to #somethinghere & #trincot.

Categories