Ask coding questions

← Back to all posts
How to execute PHP function when JavaScript if condition is met?

First of all, I an making a game using HTML, CSS, JS, and PHP. I want to append the user's score to a .txt file when the user finishes the game.

I want the PHP code to execute when the user finishes the game.

So, here's an example JavaScript code in the index.php file:

Then my code will execute after 10 seconds. But if I add PHP...

The PHP code executes before waiting 10 seconds.

I know about the sleep function in PHP, the reason I'm not using that is because the duration of time the code needs to wait for is dependent on how fast the user completes the game.

I tried putting the PHP code to an if statement, a normal function, an infinite PHP loop, you name it! All of them don't work.

Any help would be appreciated, thank you.

Answered by ch1ck3n [earned 5 cycles]
View Answer

add the php code in a sepparate file, for this example I am naming it no.php


that will send an AJAX request after 10 seconds to no.php and it will run


@ch1ck3n thank you for your help!