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> 

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.