0

I'm making a chat which is based on long polling (something like this )with PHP and jQuery. once whole page is downloaded in browser, a function makes a long polling request to the back-end with some timeout limit, when data comes from back-end it again makes the long-polling request and if any error, it will again make new long-polling request.

Problem : analyzing the traces by firebug, I've noticed that some times the long polling request is running 3 or 4 times, however it should not. there should only one long-polling request running per page.

however the code works perfectly. but long-polling request duplication is the issue.

function listen_for_message(){ 
// this functions is makes the long-polling request
$.ajax({
  url: "listen.php",
  timeout:5000,
  success: function(data) {
            $('#display').html(data);
            listen_for_message();
             }
  error: function() {
            setTimeOut("listen_for_message()",2000); // if error then call the function after 2 sec
  }
    });
    return;
}
Community
  • 1
  • 1
Bhavesh G
  • 3,000
  • 4
  • 39
  • 66

1 Answers1

1

Try to terminate requests manualy:

var connection;
function longpoll() {
   if(connection != undefined) {
      connection.abort();
   }

   connection = $.ajax({ 
       ...
       complete: function() {
          longpool();
       }
   });
}

It may also be a Firefox/firebug issue (showing aborted connections as running), test it in Chrome.

UPDATE:

"In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period." http://api.jquery.com/jQuery.ajax/

Community
  • 1
  • 1
Konrad Dzwinel
  • 36,825
  • 12
  • 98
  • 105
  • is there any way to do in code such that the code will check that if there is running a request then the function will returned else the function will called ? – Bhavesh G Jan 13 '12 at 11:10
  • You may use _connection_ variable as a flag to check if any ajax request is running and if so not allow to create a new one. Just set `connection = undefined;` in `complete` function and `return` at the beginning of `longpoll` function if `connection != undefined`. – Konrad Dzwinel Jan 13 '12 at 11:18
  • yes you are right. this is a firebug / firefox issue, chrome doesnt show multiple pending requests. thanks for your suggestion. saved my time :) – Bhavesh G Jan 13 '12 at 12:59