I'm trying to make a little and simple chat system on PhP.
My Idea was simple really, I have a form that send a text to a script in PHP and that script save the var in a Database, then the other user refresh the page to download the new message and display it on the chat box.
The problem comes, when I say refresh the page.
I just think that probably would be a problem for the user refresh the entire page every second or less thank's to a JavaScript function.
The original idea was to use setInterval()
but know I'm thinking that this can be a bad idea.
I'm not sure, but from chrome when you refresh a form it will save the form and fill it automatically, once you have finished the refresh, does every browser do that?
Willa a JavaScript function for refreshing the page be a problem for who have a really slow connection?
But most important, to fix the problem, is actually possible to just refresh a specific PHP script, that allow the user to refresh only that script and download the new message, without refreshing the entire page every second?
All the help would be appreciated.
-NOTE-
To be honest, the guy that want me to do that chat system asked me to not use JavaScript, so theoretically I'm not even allowed to use setInterval()
For refreshing part you can use <META http-equiv="refresh" content="3; URL=truc.php">
instead of setInterval (by the way, setTimeout is enough as it will occurs 1 time at each page refresh).
For the form refilling, when you submit the message it will refresh the page and free the form so it's ok. For the guy who just "read", if he started to type something and the page refresh it should keep it after refresh so il looks ok too ? But you can add autocomplete="off"
to make sure form won't suggest anything undesired.
Use the jQuery function called load(). Post a basic HTML markup of your chat page and I will edit with a specific answer.
$("#messageboard").load("chat.php #messageboard > *");
Put this code after the submit of the chat inside your ajax request to save. Change #messageboardfor the ID of the message board div that needs to be refreshed. Change chat.php for the page where the chat is displayed. In order to save loading time, you can pass on GET vars to the chat page and prevent a full load of the page and return only the messages.
You can also have the setTimeout function but both needs to run on the page so the user submitting the message sees a refresh right away (no lag)
function startTimer() {
$("#messageboard").load("chat.php #messageboard > *", function(){
//repeats itself after 1 seconds
setTimeout(startTimer, 1000);
});
}
startTimer();
In the above, 1000 is in milliseconds so equal to 1 seconds.
Using setTimeout has the advantage that if the connection hangs for some time you will not get tons of pending requests since a new one will only be sent after the previous one finished.
I am assuming you are using ajax to submit the user message so the page does not refresh every time a user posts something. Need an example for that?
<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 enter. The script will auto refresh but also refresh on a new input submit. This is just a concept. Make sure you create the server side handler to save the messages to DB.
You could use php cache to avoid refreshing the page and handle messages in a file located on the server if you just want to use php, which is server side. You can check for some file content in a while loop, and display then erase it until timeout for exemple. A submit form could write the data to the file using php. You can make XML if you want, but here is a raw way to do it : The file displaying / flushing 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()."
";
$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)."
";
}
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);
}
?>
BTW, as i said, maybe it's a bit harsh to do it this way... I think you have no option but using some client side langage to display and post data on the same page :) Good luck !
Edit :
Here is way to to it :
Make another html file, with 2 iframes : testchatframes.html :
<iframe src="testchat.php"></iframe>
<iframe src="testchatsubmit.php"></iframe>
I also modified some chunks of the initial testChat.php code to make it work on multiple "clients" (I tried on localhost), using streams instead of brutally deleting lines... I don't think this is the right way to do (maybe you should notice "the guy who want you to do that" ) this but that is quite fun and working ! It does not even seem to be so ressource expensive... :) Cheers !