PHP jQuery Long Polling Chat Application

Posted by Tejas Jadhav on Stack Overflow See other posts from Stack Overflow or by Tejas Jadhav
Published on 2012-11-17T22:48:50Z Indexed on 2012/11/17 23:00 UTC
Read the original article Hit count: 388

Filed under:
|
|
|
|

I've made a simple PHP jQuery Chat Application with Short Polling (AJAX Refresh). Like, every 2 - 3 seconds it asks for new messages. But, I read that Long Polling is a better approach for Chat applications. So, I went through some Long Polling scripts. I made like this:

Javascript:

$("#submit").click(function(){
    $.ajax({
        url: 'chat-handler.php',
        dataType: 'json',
        data: {action : 'read', message : 'message'}
    });
});

var getNewMessage = function() {
    $.ajax({
        url: 'chat-handler.php',
        dataType: 'json',
        data: {action : 'read', message : 'message'},
        function(data){
            alert(data);
        }
    });

    getNewMessage();
}

$(document).ready(getNewMessage);

PHP

<?php
    $time = time();
    while ((time() - $time) < 25) {
        $data = $db->getNewMessage ();

        if (!empty ($data)) {
            echo json_encode ($data);
            break;
        }

        usleep(1000000); // 1 Second
    }
?>

The problem is, once getNewMessage() starts, it executes unless it gets some response (from chat-handler.php). It executes recursively. But if someone wants to send a message in between, then actually that function ($("#submit").click()) never executes as getNewMessage() is still executing. So is there any workaround?

© Stack Overflow or respective owner

Related posts about php

Related posts about JavaScript