Reputation: 184
Hi this is my code working fine when you type the text it gets converted into an qr code but i want to make it automatic. I have a php function which generates random number, so instead of typing the text, the qrcode should be generated by the value of that function.
This is my html page code:
<!DOCTYPE html>
<body>
<input id="text" type="text" value="http" style="width:80%" /><br />
<div id="qrcode"></div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://davidshimjs.github.com/qrcodejs/qrcode.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
This is my javascript function :
var qrcode = new QRCode("qrcode");
function makeCode () {
var elText = <?php echo random_str(6); ?> ;
if (!elText.value) {
alert("Input a text");
elText.focus();
return;
}
qrcode.makeCode(elText.value);
}
makeCode();
$("#text").
on("blur", function () {
makeCode();
}).
on("keydown", function (e) {
if (e.keyCode == 13) {
makeCode();
}
});
and this is the php function that i want to implement so that an random number will generate and qrcode will be formed on that basis
<?php
function random_str($length, $keyspace = '0123456789')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
?>
Upvotes: 2
Views: 1932
Reputation: 604
It depends on how your html is rendered
1- if it's from php and you this function is in same file or can be called from this php file, you can do that:
<script>
var qrcode = new QRCode("qrcode");
qrcode.makeCode('<?php echo random_str(3); ?>');
</script>
2- if it's an html file you can not call the function, you can use ajax to call a php file which give you the value of random and use it
Upvotes: 1
Reputation: 9525
When you were using the input-based version you coded the makeCode() function to pull the value for the QRCode from the input box. Now that you are using a literal value you need to modify the makeCode() in respect of how it works with the source number - now a javascript literal value and not a control.
function makeCode () {
var elText = "<?php echo random_str(6); ?>" ; // note quotes around random no.
if (elText.length === 0) { // is the random string zero length
alert("Random number is blank - weird !");
return;
}
qrcode.makeCode(elText);
}
The quotes around the random number from php will protect you from the risk of it returning a blank. I don't know how likely that is but if it did happen then the JS would fail. And since there are no numeric operations on it we can just treat it as a string. In that case we can test it's length and decide from there is we need to make the QRCode.
Upvotes: 2