0

So I am building a real-time chatroom, and this is my code so far. I am trying to create exit messages, in that when someone closes the tab or goes to a different page, it inserts a message to the database.

This is what I have so far:

<?php
session_start();
require('./essentials.php');
welcome_message(0, 11, true); //custom function that I wrote in ./essentials.php
?>

<html style="background-color:#202020;">

<head>
    <title>Programming - Parity Chatroom</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src='./socket.js'></script>
    <script type='text/javascript'>
        websocket.onopen = function() {
            alert('Connected to server!');
            conn.send("Someone joined!");
        }
        websocket.onmessage = function() {
            if (!document.hasFocus()) {
                var audio = new Audio("./notification.wav");
                audio.play();
            }
        }
        websocket.onclose = function() {
            setTimeout(function() {
                window.location.reload();
            }, 5000);
        }
        window.onbeforeunload = function() {
            conn.close(1000, 'Closed page');
            <?php exit_message(); /* function to insert exit message to db */ ?>
        }
    </script>
</head>
<FRAMESET cols="20%,*">
    <FRAME src="sidebar.php" id='sidebar' style='overflow:hidden'>
    <FRAMESET rows="*,9%">
        <FRAME src="messages.php" id='messages'>
        <FRAME src="newmessage.php" id='newmessage' style='overflow:hidden'>
    </FRAMESET>
</FRAMESET>
</html>

So the code runs just fine, but I think there is an issue with the order in which the code runs. Specifically, the javascript onbeforeunload event seems to fire whenever I visit the page. I suspect that this has to do with the fact that PHP code loads and executes when the page loads, considering that it is a server-side language.
Is there a way to slow that down and make the script run in order?


Any help would be greatly appreciated!

Adi B.
  • 37
  • 4
  • Um, why are you not using the disconnected event on the server?? PHP runs before the page loads... Page Life Cycle 101 – epascarello Nov 16 '21 at 01:24
  • Code in `` runs when the page is created, not when the client executes the JavaScript. – Barmar Nov 16 '21 at 01:25
  • You should use an AJAX request on your `` window.onbeforeunload`` function to execute the ``exit_message();`` in PHP. – Dula Nov 16 '21 at 01:53
  • Mandatory reading: [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – CBroe Nov 16 '21 at 07:52

0 Answers0