1

i have a simple chat and the way i do thinks now is like this:

function ajax() { 
    $.ajax({  
        url: '/chat/index/json',
        type: 'POST',
        dataType: "json",
        success: function(data) {   
           // output the html to my chat window
        }
    });
    window.setTimeout("ajax()",5000);
}


$(document).ready(function() {
    ajax();
    $('#chat').submit(function(e) { 
        e.preventDefault();
        sendMessage();
    });
});


function sendMessage()
{   
    // grab the values from text textarea
    $.ajax({
          url: '/chat/index/jsave',
          type: 'POST',
          dataType: "html",
          data: message,
          success: function(d) {  
              // empty the textarea 
              ajax(); 
          }
    });
}

i basically call the ajax(); function every 5 seconds. Im not sure if this is the best way to do this because i have a request to the server every 5 sec.

is there a better way of doing this?

thanks

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337
  • 2
    I think you are looking for this http://stackoverflow.com/questions/333664/simple-long-polling-example-code – MadRabbit Mar 10 '12 at 07:00
  • Unrelated to Ajax, best practice on `setTimeout` is to pass a function reference rather than a string: `window.setTimeout(ajax,5000);` – nnnnnn Mar 10 '12 at 07:15

1 Answers1

1

First of all, try to use GET instead of POST. GET will work faster and as you don't send security protected data you can use it. If you have chat...you must have a request to server every n seconds.
Why GET method is faster than POST?

Community
  • 1
  • 1
Pave
  • 2,347
  • 4
  • 21
  • 23
  • Not agree with 'if you have a chat... you must'. You can, but as alternative you can use long polling or web sockets – MadRabbit Mar 10 '12 at 08:00