如何在javascript函数中设置php变量?

时间:2018-04-12 06:54:51

标签: javascript php ajax one-time-password

我想创建一个OTP发送者和检查者 代码是这样的:

<?php
	$Mail = "someone@gmail.com";
		$OTP = mt_rand();
		$subject = "OTP from HelloBuddy.co.in";
		$txt = "You have recieved OTP from HelloBuddy.co.in. The OTP is $OTP. Please enter the OTP in the website. Please note that the OTP will expire in 100 seconds.";
    if (mail($Mail,$subject,$txt)){
			echo "<p>OTP has been successfully sent<br>The OTP will expire in <span id='xpire'>100</span> seconds.<br>Please enter the OTP here:<input type='number' name ='OTP'></p>";
			echo "<script>
					var a = 99;
					var x = setInterval(cdown, 1000);
					function cdown(){
						if (a>=0) {
							document.getElementById('xpire').innerHTML = a;
							a=a-1;
						} else {
							clearInterval(x);
							clearOTP()
						}
					function clearOTP{
					$OTP = '';
          }
          </script>";
    }else{
   die(ERROR);
}
?>

我正在使用xampp服务器并正确配置了所需的文件 我想在100秒后清除OTP,但不能,也许是因为它在javscript函数中 如果可能,请提供AJAX。

3 个答案:

答案 0 :(得分:1)

你不能用javascript设置php变量。

PHP将在服务器端执行,javascript在客户端执行。因此,在调用javascript之前,所有PHP代码都已执行。

$ OTP变量尚未保存。因为代码在服务器端执行并且将被垃圾收集。如果要保存和删除OTP,则应使用某种数据库。

答案 1 :(得分:0)

在脚本之前使用php标签,然后连接php变量

试试这个,

<?php
$Mail = "someone@gmail.com";
    $OTP = mt_rand();
    $subject = "OTP from HelloBuddy.co.in";
    $txt = "You have recieved OTP from HelloBuddy.co.in. The OTP is $OTP. Please enter the OTP in the website. Please note that the OTP will expire in 100 seconds.";
if (mail($Mail,$subject,$txt)){
        echo "<p style='color:green; font-size:30px; text-align:center; text-decoration: underline;'>OTP has been successfully sent<br>The OTP will expire in <span id='xpire'>100</span> seconds.<br>Please enter the OTP here:<form method ='POST' action = ''  style='text-align:center'><input style='color:green; font-size:30px; text-align:center;text-decoration: underline;'type='number' name ='OTP'><input style='color:white; background-color:#4CAF50;border:2px #4caf50 solid; font-size:30px; cursor:pointer;' type='submit' value='Check'></form></p>";
        ?><script>
                var a = 99;
                var x = setInterval(cdown, 1000);
                function cdown(){
                    if (a>=0) {
                        document.getElementById('xpire').innerHTML = a;
                        a=a-1;
                    } else {
                        clearInterval(x);
                        clearOTP()
                    }
                function clearOTP{<?=$OTP ='';?>}
      </script>

<?
    }
?>

答案 2 :(得分:0)

Php变量只能在JS中使用,不能被操纵(初始化/更新)。 上面的任务可以通过ajax使用,将otp的值保存在js中并重置,使用ajax执行其他操作,如OPT验证。