I have a chat in my browser game. How can I implement chat updates without rebooting? Tried using jquery+ajax - failed.


 window.onload = function () { var loader = document.getElementById('chat_t'); setInterval(function () { loader.load(); }, 1000); } 


 $(document).ready(function () { $('#load').click(function () { $(this).load('/game.php?the=chat'); }) }); 
  • 2
    > I tried using jquery + ajax not> it turned out. We show the sample code, and ask where the jamb is, what's not done, tell me please ?! - Palmervan

2 answers 2

 setTimeout(function(){ $.get('chat.php?onlynew', function(data){ $('#chat').append(data); }); }, 10000); 

onlynew gives the chat script ( chat.php ) an instruction to output only new messages (how to determine which new ones - think for yourself), #chat is the element where messages are displayed, data is the html-code of messages (it's easier to connect the template engine).
Alternatively, the result can be returned in the form of JSON and parsed it on the client. Traffic will eat less.

  • setTimeout will check once. The page was loaded and for all its existence it will be updated once. - Shevsky

Simply. We make a script that checks for new messages, if not - an empty array, if there is - an array with messages. Next, with the help of the JS mutim setInterval every N seconds with access to this script, respectively, we display new messages.

  • <script type = "text / javascript"> setTimeout ("window.location.reload ()", 10000); </ script> So? - Riolu
  • @Riolu, vatafak man, I did not write this! check.php: echo getNewMessages (); // Get the list of new messages chat.php: setInterval ("updateChat ();", 10000) // Check for new messages and write updateChat: function () {$ .getJSON ('check.php', function (data) {// i love jQ if (data.length> 0) $ ('# chat'). append (data.text);}); } Something like that. - Shevsky
  • 2
    setInterval with ajax is a sign of bad taste. - ling
  • @ling, well, tell me ka then still options. - Shevsky