Purpose: Live PHP chat system
About the code:
- The first part searches for older messages and displays them (it works). It also gets the ID of the last message that already exists.
- The second part searches for new messages (their ID is greater than the one received on page loading).
Problem:
- The AJAX request doen't seem to be executed since new text isn't displayed. Also, anything written after the div id="verification" doesn't work: for ex I tried displaying an alert, but without success.
-
I get an error in the Chrome console: Uncaught syntax error: Invalid or unexpected token on this line (and it might be beacuse of the
'<div>'
in the echo statement:echo '<div>' . $row['com'] . '</div>';
Main code:
<?php
include('config.php');
$query = "SELECT MAX(id) FROM comments";
$res = mysqli_query($connect,$query);
$rez = mysqli_fetch_assoc($res);
$id = $rez['MAX(id)'];
$query1 = "SELECT com FROM comments";
$res1 = mysqli_query($connect,$query1);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
.verification{
overflow-y:scroll;
height:300px;
width:100px;
}
</style>
</head>
<body>
<div id="verification">
<?php
while($row = mysqli_fetch_assoc($res1))
{
echo '<div>' . $row['com'] . '</div>';
}
?>
</div>
<script>
setInterval(function () {
$.ajax({
type: "GET",
url: "getmsg.php?id=<?php echo $id; ?>",
dataType: "json",
success: function(data) {
for (i = 0; i < data.length; ++i) {
var msg = data[i][0];
$("#verification").append('<div class="left spotmsg"><div class="message">
<p class="txt">'+msg+'</p></div></div>');
}
}
});
}, 1000);
</script>
</body>
</html>
getmsg.php:
<?php
include('config.php');
$id1 = $_GET['id'];
$query = "SELECT com FROM comments WHERE id > $id1";
$res = mysqli_query($connect,$query);
while ($row = mysqli_fetch_all($res)) {
header('Content-Type: application/json');
ob_end_clean();
echo json_encode($row);
}
?>