Simple Comet Implementation Using PHP and jQuery

I have been researching about the Comet application model recently. I stumbled upon a great article from Zeitoun.net in which their AJAX implementation example is written in PHP and ProtoType (a JavaScript Framework). I decided to modify the Classic AJAX/ProtoType Implementation to use  jQuery – my JavaScript framework of choice thus far. This is only the client side of the entire architecture when you’re dealing with huge databases and web services but at least this gets you started.

We’ll be using 3 files here:

  • backend.php
  • data.txt
  • index.html

Both backend.php and data.txt stayed the same as the original example. I only modified index.html’s JavaScript block to look  like this:

var Comet = function (data_url) {
this.timestamp = 0;
this.url = data_url;
this.noerror = true;

this.connect = function() {
var self = this;

$.ajax({
type : 'get',
url : this.url,
dataType : 'json',
data : {'timestamp' : self.timestamp},
success : function(response) {
self.timestamp = response.timestamp;
self.handleResponse(response);
self.noerror = true;
},
complete : function(response) {
// send a new ajax request when this request is finished
if (!self.noerror) {
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function(){ comet.connect(); }, 5000);
}else {
// persistent connection
self.connect();
}

self.noerror = false;
}
});
}

this.disconnect = function() {}

this.handleResponse = function(response) {
$('#content').append('
<div>'
+ response.msg + '</div>
'
);
}

this.doRequest = function(request) {
$.ajax({
type : 'get',
url : this.url,
data : {'msg' : request}
});
}
}

var comet = new Comet('./backend.php');
comet.connect();

For more details, check out the article where I based this from. Happy hacking!

jQuery Comet on GitHub

Download:

Leave a comment ?

16 Comments.

  1. Thanks for sharing the jQuery version of Comet with PHP ;) . I was looking forward to convert it, but I google it before. Great job!

  2. You’re welcome. Glad to help. :)

  3. Jitesh Lalwani

    Hello Ardy,

    Its great to read the article, its solve much of my problem, though I have 2 questions, if you can solve it then it will be great:

    1) I am looking for live updates using Comet (Much Like Facebook where if one User Post a message on site then Server should refresh the client Page Asynchronously). It is possible by this approach and how. AFAIK, Comet cannot be done on Apache due to Single Threaded model and hence is there a need to do reverse-proxy between jetty server and Apache?

    2) Also, I want to implement Chat system in php application, does the above solution will work and handle the necessary load?

    Looking forward for your reply, thanks once again for the article :)

  4. Hello !

    Thank you very much for your work, it’s great !
    I am using it and it’s working fine.

    But now, I have a problem :
    I would like to pass in the URL the name of the data where the messages are written (data.txt). I have modified the backend script to get the name passed in the URL.

    I have added :
    $nameFile = isset($_GET['nameFile']) ? $_GET['nameFile'] : ”;

    and im constructing the filename like this :
    $filename = dirname(__FILE__).$nameFile.’.html’;

    When I do so, the messages are written in the file without any problems, BUT, when I do like this, my message never appears in the chat as the javascript function handleResponse() is no longer called in the html file ! :/

    If I define the filename directly in the code ($filename = ‘myFile.html’), it’s working fine. Does anyone know why I cant use the GET parameter i am reading from the url to define the name of the data?

    Thank you !

  5. Hi Sebastian,
    Make sure that your folder is writeable.
    And most importantly make sure that you pass the parameter correctly by updating the doRequest method:

      this.doRequest = function(request) {
          $.ajax({
            type : 'get',
            url : this.url,
            data : {'msg' : request, 'nameFile' : 'myfile'}
          });
      }

    Cheers,
    Ardy

  6. Hi Ardy,

    Thank you for your quick answer !
    Actually I am sure that my file is writeable, and that the name is properly passed as a parameter.
    When I write something in the chat, the content is saved in the right file. But handleResponse is never called, even if the file has been modified ! I have the impression that something is going wrong with the file modification detection (as if in backend.php, something would go wrong with filemtime when I pass the name of the file with as a parameter), but indeed I have no idea why :/

  7. Hi Jitesh,
    Sorry for the late reply.

    About your 1st question: That’s what I’m curious about as well. Not sure how facebook does it, I haven’t tried implementing it myself. The only solution I can think of is Java 7′s asynchronous channels and sockets. You can check that out. But I think it is possible with Java 6 as well.

    2nd question: The example above is only for demo purposes and will work for small chat systems (e.g. office intranet chat systems). You’ll need a robust backend like Java or C to talk to php and implement the chat system if you’re looking to scale to a big chat system in which case, php will only act as the mediator.

    Cheers,
    Ardy

  8. Hi Sebastian,
    You are right. I’m able to reproduce that bug. I’ll take a look into that :)

  9. Hello !
    Sorry for my bad english, I’m a french developper.

    Your mistake is on the following line:
    $filename = dirname(__FILE__).$nameFile.’.html’;
    for example:
    dirname(__FILE__) = folder
    $nameFile = myFile
    dirname(__FILE__).$nameFile.’.html’ = foldermyFile.html
    So, this line must be:
    $filename = dirname(__FILE__).’/’.$nameFile.’.html’;

  10. Facebook (and Hotmail too) use long-polling, much like this example here, where they leave a long running xhr open until either 1. their server-side code detects an update at which time it posts it back to the response and then starts the request over, or 2. the request times out at which point they immediately start it over. they’re not true push-state. (you can see it in FireBug, Fiddler, Tamper Data, or Chrome/Safari dev tools)

  11. Hi Kelly,
    Yes you’re right. I think I didn’t wait long enough to see those pull requests in the js console from Facebook. Realized that it took a few more seconds for the pull requests to appear after Facebook’s page load. Thanks for clarifying :)

  12. Thank You….

  13. Thank you for the example and explanation, I was clear about the methods comet

  14. Great article !
    Easy to understand, easy to implement.
    Thanks
    Fabio

    PS I love jquery and I need Comet too.

    [WORDPRESS HASHCASH] The poster sent us ’1881865295 which is not a hashcash value.

  15. Hi Ardy thanks for sharing this JQuery version, but it’s not working in my site.
    if you have any time you could check it on http://erainformatika.com/comet-ajax/

    Thanks in advance

  16. The script works great but only for few minutes :cry: , the thing is that the session expire and the script does not work properly. In any case the poolling refresh the function “this.disconnect = function() {}” is empty.

    How can I do a refresh cycle after 30 seconds ?

    thank you!

Leave a Comment


4 + = seven


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>