5

I'm doing a long poll method chatroom. But it seems that, when a long poll occurs and I refresh the page in chrome OR i try to send another async request everything times out (i.e i cant load my domain again until i close/reopen the browser).

My client side code is:

 $(document).ready(function() {
    setTimeout(
      function () {
        longPollForMessages();
      },
      500
    );
  });

function longPollForMessages()
{
  $.ajax({
    url: url,
    dataType: 'json',
    success: function(data) {     
        $('#chat_messages').append('<div>'+data.messages+'</div>');

        longPollForMessages();
    }
  });
}

And my serverside:

while(true) {
      $messages = $db->getMessages();

      if (!$messages || sizeof($messages)==0) {
        sleep(1);
      } else {
        echo '{"message":'.json_encode($messages).'}';
        die();
      }
    }

Any ideas? Assume no syntax errors.

Zak Henry
  • 2,075
  • 2
  • 25
  • 36
Andy Hin
  • 30,345
  • 42
  • 99
  • 142
  • Try putting a `break;` after the `echo` in the serverside code – The Scrum Meister Feb 11 '11 at 04:04
  • Thanks four your answer :) I actually had that but forgot to include in my question code. So that is not the issue. – Andy Hin Feb 11 '11 at 04:05
  • 2
    Guys, I figured it out from this question: http://stackoverflow.com/questions/4457178/long-polling-locking-up-other-ajax-calls - php locks a given session until the page is done loading so the second ajax call wasn't able to go through. You have to release the lock by calling session_write_close(); – Andy Hin Feb 11 '11 at 04:15
  • You are aware that you send back the message as `message` but access it in your JavaScript with `messages`? – alex Feb 11 '11 at 04:21
  • alex - yeah sorry. i just rewrote the code quickly because i didn't want to paste everything (you probably don't want to read all of it). =) – Andy Hin Feb 11 '11 at 05:24
  • @Andy, post an answer with what you say in your comment, and accept it as the correct answer. – Gabriele Petrioli Feb 12 '11 at 12:59

2 Answers2

0

I can see you have already answered your own question, but I recently had a similar problem and found another way to handle it is to disable the setTimeout on ajax call, then restart it on success. That way you aren't pinging your server for information when it isn't ready to give it.

Zak Henry
  • 2,075
  • 2
  • 25
  • 36
  • AFAIK, the setTimeout only calls the function once. So you still need to restart the call after a successful request. Can you elaborate a bit more on your answer? – Andy Hin Feb 15 '11 at 19:58
0

I figured it out from this question: stackoverflow.com/questions/4457178/… - php locks a given session until the page is done loading so the second ajax call wasn't able to go through. You have to release the lock by calling session_write_close();

Andy Hin
  • 30,345
  • 42
  • 99
  • 142