Potato Potato - 4 months ago 22
jQuery Question

How to I refresh the chat using javascript?

Okay, So I am trying to create a simple chat for my website but I don't know how to make it so when someone sends a message it will show on other peoples chat so for example I say hello on one browser but it does not show on another browser until I manually refresh the page.

I know there is AJAX to refresh the div of the chat but everything I tried does not seem to work and I don't know why.

Here is my index file

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
setInterval( refreshMessages, 1000 );
function refreshMessages(){
$.ajax({
url: 'chat.php',
type: 'GET',
dataType: 'html'
})
.done(function( data ) {
$('#chat').html( data ); // data came back ok, so display it
})
.fail(function() {
$('#chat').prepend('Error retrieving new messages..');
});
}
</script>

<div id="chat"></div>


It does not show the chat at all and I don't know why because the file is in the same folder as the index.php

if I put the chat code inside the index file it works fine.

Here is the chat.php file

`$messages = get_msg();
foreach($messages as $message) {
echo '<p><strong>' . $message['sender'] . ' - </strong></p>';
echo '<p>' . $message['message'] . '<br /><br />';
}`

Answer

Because you are using jQuery 1.3:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>    

You cannot use done and fail. These are not available in jQuery 1.3.0

Use instead: success and error.

Referring to

A. Wolf comment try to take a look to how-do-i-implement-basic-long-polling

The corrected snippet only for the ajax call:

setInterval(refreshMessages, 1000);
function refreshMessages() {
  $.ajax({
    url: 'chat.php',
    type: 'GET',
    dataType: 'html',
    success: function(data) {
      $('#chat').html(data); // data came back ok, so display it
    },
    error: function() {
      $('#chat').prepend('Error retrieving new messages..');
    }
  });
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>

<div id="chat"></div>