简体   繁体   中英

Php inside js condition

I have a js countdown with php fucntion inside a js condition. Evething is good except that when reloading the page the php fucntion runs anyway.

var countDownDate = new Date("2020/04/25 16:15:25").getTime();
var x = setInterval(function() {
    var now = new Date().getTime();
    var distance = countDownDate - now;
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    document.getElementById("demo").innerHTML = hours + "h " + minutes + "m " + seconds + "s ";
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "SESSION EXPIRED";
        <?php block_user(2); ?>
        document.getElementById("demo2").innerHTML = "User 2 blocked";
    }
}, 1000);

If it's the case that block_user(2) actually blocks the user in the database it would appear that it's being executed in the first page load. PHP will execute on the page load. It won't be deferred to the conditional in the javascript. If your function prevents you from blocking a user more than once, that's why it's not working if you reload the page. You would have to have some asynchronous call to a PHP script.

if (distance < 0) {
  clearInterval(x);
  document.getElementById("demo").innerHTML = "SESSION EXPIRED";

  $.post("block_user.php", {user_id:2}).done(function (response) {console.log(response);});

  document.getElementById("demo2").innerHTML = "User 2 blocked";
}

Then block_user.php would lookup the user_id in $_POST['user_id'] and execute block_user($_POST['user_id']);

This is a simplified solution which doesn't take into account security or sanitizing your post variables but it's a start to solve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM