JS+PHP消息应用发送后消息秒消失问题求助
Great job building your JavaScript/PHP chat app—let's tackle that annoying "message vanishes" issue head-on. The root cause is a simple typo in your get-message.php file that breaks the message-fetching logic, and your recurring update() function is wiping out the message area every 2.5 seconds as a result.
The Exact Problem
Look at this line in get-message.php:
while($r = $resut->fetch_row()) {
You misspelled $result as $resut! This causes PHP to throw an undefined variable error, so the loop never runs to fetch messages from the database. When update() fires every 2.5 seconds, it requests this broken script, gets an empty response, and sets msgarea.innerHTML = output (where output is empty). That's why your manually added message gets erased almost immediately.
Step-by-Step Fixes
1. Fix the Typo in get-message.php
Correct the variable name to $result so the loop can properly fetch and return messages:
<?php $db = new mysqli("localhost","root","","het_msg"); if ($db->connect_error) { die("couldnt connect"); } $username = stripslashes(htmlspecialchars($_GET['username'])); $result = $db->prepare("SELECT * FROM messages"); $result->execute(); $result = $result->get_result(); // Fixed variable name here while($r = $result->fetch_row()) { echo $r[1]; echo "\\"; echo $r[2]; echo "\n"; } ?>
2. (Optional but Recommended) Avoid Duplicate Messages
Right now, you add the message manually in sendmsg() and update() will pull it from the database. This will create duplicate messages once the typo is fixed. Instead, remove the manual HTML addition and just trigger update() after sending:
function sendmsg() { var message = msginput.value; if (message != "") { var username = getcookie("messengerUname"); var xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { msginput.value = ""; // Refresh messages from database instead of adding manually update(); } } xmlhttp.open("GET","update-message.php?username=" + username + "&message=" + message,true); xmlhttp.send(); } }
This way, all messages come from the single source of truth (your database), keeping the UI consistent.
3. (Optional) Enable PHP Error Reporting
To catch typos like this faster during development, add error reporting at the top of your PHP files:
<?php error_reporting(E_ALL); ini_set('display_errors', 1); // Rest of your code... ?>
Bonus: Improve Update Efficiency (Long-Term)
Right now, update() pulls all messages every 2.5 seconds. As your chat grows, this will get slow. Instead, track the last message ID you've loaded, and only fetch messages newer than that ID. This reduces bandwidth and makes the app smoother.
内容的提问来源于stack exchange,提问作者user9182780

