Jump to content

body onload / onunload - how to run a php script?


strobic

Recommended Posts

I have this code. Why aren't the php scripts working when executing the body onload or onunload functions?

 

<head>
<script language="javascript">
<?php function hello() {
$fp = fopen("counter.txt", "r");
$count = fread($fp, 1024);
fclose($fp);
$count = $count + 1;
echo "<p>Number of users online now:" . $count . "</p>";
$fp = fopen("counter.txt", "w");
fwrite($fp, $count);

fclose($fp);
alert("Welcome to My Page");
}
?> 

<?php function goodbye() {
$fp = fopen("counter.txt", "r");
$count = fread($fp, 1024);
fclose($fp);
$count = $count - 1;
$fp = fopen("counter.txt", "w");
fwrite($fp, $count);

fclose($fp);
  alert("Goodbye!");
}
?> 
</script>

</head>
<body onload="hello()" onUnLoad="goodbye()">


</div>
</body>
</html> 

Link to comment
Share on other sites

You cannot call php functions (which execute on the server) with Javascript events (which execute on the client) without making a new request.

 

This can be done via either a complete new request or Ajax. Either way, it's a client side issue and your question belongs in a client side board.

Link to comment
Share on other sites

Thanks, what i'm trying to achieve is a current online count of users on the page. This is stored in a text file. So when a user opens or closes the page it will increase and decrease the count. But I can't see how to amend this using Ajax to run the PHP script upon the javascript event.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.