Although I believe my code is correct, I am not very familiar with AJAX and have been struggling for hours to get it right. I've tried various approaches, including using filters, but nothing seems to work. The issue I'm facing is that the chat messages are not showing up as they normally would when I refresh the page.
My goal is simply to create a chat interface. Here is a live example of the problem:
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
dataType: "html",
url: 'chat.php?r=' + <?php echo "'" .$_GET['r']. "'"; ?> ,
success: function(data) {
var trim = $(data).find('.message_window');
$('.message_window').replaceWith(trim);
}
});
}, 1000);
});
This is what's inside my body tag:
<div class="wrapper">
<div class"inbox_window" id="style-3">
</div>
<div class="message_window" id="style-3">
<table width="100%">
<p class="talking_to"><?php echo getFirstnamebyID($_GET['r']); ?></p>
<?php echo displayMessages(); ?>
</table>
</div>
<form class="submit_form" method="post" <?php echo 'action="chat.php?r='.$_GET['r'].'"' ?>>
<input type="text" name="message" placeholder="Type message here" />
<input type="submit" value="Send" name="s_say"/>
</form>
</div>
This is the PHP function for displayMessages():
function displayMessages() {
$user_id = getUserID();
$sql = mysql_query(strip_tags("SELECT * FROM inbox WHERE (send_id='".$user_id."' OR send_id='".$_GET['r']."') AND (rec_id='".$_GET['r']."' OR rec_id='".$user_id."') ORDER BY timestamp;"));
if (mysql_num_rows($sql) != 0) {
while($row = mysql_fetch_assoc($sql)) {
if ($row['send_id'] == $user_id) {
echo '<tr><td><p class="sm">'. $row['messages'] .'</p></td></tr>';
} else if ($row['send_id'] == $_GET['r']) {
echo '<tr><td><p class="rm">'. $row['messages'] .'</p></td></tr>';
} else {
echo "Unable to display messages.";
}
}
} else {
echo "Be the first to say hello!";
}
}
I would greatly appreciate any assistance as I am feeling quite frustrated with this issue.