Building a chat system based on AJAX. How to avoid page refresh on submitted content and show new posts in real time

I am trying to create a small and simple chat system in PhP.
My idea was simple actually, I have a form that sends text to a script in PHP and that the script stores the var in the database, then another user refreshes the page to load a new message and display it on the chat.
The problem comes when I talk about refreshing the page.
I just think it will probably be a problem for the user to refresh the entire page every second or less thanks to the JavaScript function.
The original idea was to use setInterval()

it but know I think it might be a bad idea.
I'm not sure, but from chrome, when the form is updated, it will save the form and auto-fill it, once you finish updating, does every browser do this?

Willa JavaScript function to refresh the page will be a problem for those with really very slow connections?

But most importantly, to fix this issue, is it really possible to just update a specific PHP script that allows the user to update only that script and load a new post without refreshing the whole page every second?

All help would be appreciated.

-DEFINITION-

Honestly, the guy who wants me to make this chat system asked me not to use JavaScript, so in theory I am not even allowed to usesetInterval()


+3


source to share


3 answers


To update a part, you can use <META http-equiv="refresh" content="3; URL=truc.php">

setInterval instead (by the way, setTimeout is enough, as it will happen 1 time each time the page is refreshed).



To fill out the form, when you submit a message, it will refresh the page and free up the form to be fine. For a guy who was just "reading", if he started typing something and refreshing the page, he should keep it after refresh, so does it look okay? But you can add autocomplete="off"

to make sure the form doesn't suggest anything unwanted.

0


source


Use a jQuery function called load (). Submit basic HTML markup on your chat page and I'll edit with a specific answer.

$("#messageboard").load("chat.php #messageboard > *");

      

Place this code after chat sending in your ajax request to save. Change #messageboard to the ID of the message board div you want to update. Modify chat.php on the page where the chat is displayed. To save load time you can pass GET vars to the chat page and prevent full page load and only return messages.

You can also have a setTimeout function, but both must be done on the page so that the user sending the message will immediately detect the update (no lag)

function startTimer() {
     $("#messageboard").load("chat.php #messageboard > *", function(){
          //repeats itself after 1 seconds
          setTimeout(startTimer, 1000);
     });
}

startTimer();

      



In the example above, 1000 is equal to milliseconds equal to 1 second.

Using setTimeout has the advantage that if the connection hangs for a while, you won't get tons of pending requests, since a new one will only be sent after the previous one completes.

I am assuming you are using ajax to send a custom message so that the page does not refresh every time the user types something. Need an example?

<html>
<head>
<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>

<script>
    $('document').ready(function(){
        $('#submit').click(function(){
            var message = $('#message').val();
            $('#message').reset();
            $.post('chat.php',{message: message},function(response){
                $("#messageboard").load("chat.php #messageboard > *");
            });
        })
        $('#message').keypress(function(e){
            if(e.which == 13){//Enter key pressed
                var message = $('#message').val();
                $('#message').reset();
                $.post('chat.php',{message: message},function(response){
                    $("#messageboard").load("chat.php #messageboard > *");
                });
            }
        });

        function startTimer() {
          $("#messageboard").load("chat.php #messageboard > *", function(){
              //repeats itself after 1 seconds
              setTimeout(startTimer, 1000);
          });
        }

        startTimer();
    });
</script>
</head>
<body>
<div id="messageboard"></div>
<input type="text" placeholder="Message" id="message"><input value="submit" type="button" id="submit">
</body>
</html>

      

The above will trigger a POST on the submit button, but also if the user hits the enter button. The script will automatically update, but also update on new input. This is just a concept. Make sure you create a server side handler to save messages to DB.

0


source


You can use php cache to not refresh the page and process messages in a file located on the server if you just want to use php which is server side. You can check the contents of some file in a while loop and display it, then delete it until the timeout appears. The submit form can write data to a file using php. You can do XML if you like, but here's a rough way to do it: File displaying / clearing data in your browser: testChat.php

<?php
$timeout=200;
set_time_limit($timeout+1);//Maximum execution time.
flushBrowser();//Print space chars to have cache flush on browsers.
$str='';
while ($timeout>0){
    //Flush data to display
    ob_flush();
    flush();
if ($str!=checkPostMsgQueued())
echo checkPostMsgQueued()."\n";
$str=checkPostMsgQueued();
    //wait...
    sleep(1);
    $timeout-=1;
}
ob_end_flush();


//Many browsers seems to receive some data before flushing.
function flushBrowser(){
if (ob_get_level() == 0) ob_start();
echo str_pad('',4096)."\n";   
}
function checkPostMsgQueued(){
        $filename="testChat.txt";
        if (file_exists($filename)){
            $stream=fopen($filename, 'r');
            $str=stream_get_line($stream,128);
            fclose($stream);
        }
        return $str;
}

      

testchatsubmit.php:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form action="testChatSubmit.php" method="post">
    <input type="text" name="message" id="message">
    <input type="submit" name="submit">
</form>
</body>
</html>
<?php
if (isset($_POST['message'])){
$fp = fopen('testChat.txt', 'w');
fwrite($fp, $_POST['message']);
fclose($fp);
}
?>

      

By the way, as I said, maybe it's a little tough to do it like this ... I think you have no choice but to use some kind of client interface to display and publish data on the same page.:) Good luck!

Edit:

Here is the path to it:

Create another html file with two iframes: testchatframes.html:

 <iframe src="testchat.php"></iframe> 
 <iframe src="testchatsubmit.php"></iframe>

      

I also modified some of the testChat.php source code snippets to make it work with multiple "clients" (I tried on localhost) using streams instead of brutally deleting lines ... I don't think this is correct (perhaps you should notice "the guy who wants you to do it"), but it's pretty fun and works! It doesn't even seem too expensive ... :) Cheers!

0


source







All Articles