I’m working on a live discussion form. The page loads the threads from MySQL, and refreshes via AJAX every 4 seconds. After the last comment on each thread, there’s a text input for comments (very similar to Facebook).
Everything works fine, except that when the user is writing in the input and the page refreshes, the message disappears. Security and privacy is the main goal on this project, that’s why I don’t want to use cookies. I have tried many solutions, and searched several hours for a solution but nothing seems to work.
- Is it a possible solution to
$_postevery time that page refreshes? - In case of caching the entered values and retrieving them from
$_sessionor local storage, can anyone suggest a more specific approach? i.e: where to put the listeners 🙂 - I’ve tried to make a function that prevents reloading the page if the value of the input is different to “”, but even this didn’t work for me.
Here is my refresh code:
<script type="text/javascript">
var PHP = "msgboard.php";
function updateShouts(){
$('#msgboard').load(PHP);
}
window.setInterval( "updateShouts()", 4000 );
</script>
And here is the main PHP function:
while($row = mysql_fetch_array($resultados)) {
echo '<div class="post">
<div class="user"><b>'.$row["user"].'</b></div>';
echo ' <div class="txt">'.$row["msg1"].'</div>
</div>';
$sql2="SELECT * FROM table WHERE masterid = '".$row['id']."'ORDER BY id ASC";
$resultados2 = mysql_query($sql2);
while($row2 = mysql_fetch_array($resultados2)) {
echo '<div class="comment">
<div class="txt"><b>'.$row2['user'].'</b>';
echo ' '.$row2['msg1'].'</div>
</div>';
}
echo '<div class="commentform">
<form action="board.php" method="post">
<input type="text" size="75" name="message" id="message1">
<input type="hidden" name="masterid" value="'.$row['id'].'">
<input type="submit" name="Submit" value="Enviar"></form>
</div>' ;
}
Thanks in advance!
As @aziz pointed out in the comments, if you just want to update the comments, you only need to update that part of your page.
Step 1: Add a container to the comments so you can target the update to that container
You will notice there is now a new div
<div id="comments_contaner">in the code which will contain all the comments.Also when you are outputting HTML, it is easier / more legile to just close the PHP tag and use
<?= $variable ?>if you need to place a PHP variable in the HTML.msgboard.php:
Step 2: Create a PHP function to update the comments
This function will only output the comments, it will need the
masteridas a parameter to know which comments to output.updateComments.php:
Step 3: Call the PHP update function in your script targeting the container div
You will need to pass the
$row['id']as a parameter in the URLPD: I have not tested this code, it is just to show you the main idea.
EDIT: Corrected variable names and added comment.