0

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);
1
  • 1
    Any PHP code is run on the server before the JS is passed back to the browser. Commented Apr 25, 2020 at 14:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i did that bug i got an error : Uncaught TypeError: Cannot read property 'post' of undefined
Sorry I guess I had assumed you were using jQuery. I think I must have read that in the other reply and thought you mentioned it in your post. If you aren't going to use jQuery in your code I suggest you search ajax requests with vanilla javascript. Same principle though. When the countdown is done.. (distance < 0) then you execute the ajax request which then executes your block_user php code on the server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.