Question

I'm been trying for many hours to get this working, just a basic long polling to a php script on the web server. I am testing it by having a text file which I check the last modified time of and compare it to the time the javascript sends a request. If the date of the file is newer then I send back a message "update". When I load the page in my browser it sends the request and waits as expected which I can verify using Chrome dev tools but then when I edit the file (ie. change the modified date) the update.php script never echos the update message. Instead it just continues until it times out.

I think it might have something to do with caching because if I copy the URL that the JS requests into a separate tab it also doesn't respond but if I change the random parameter that jQuery attaches to prevent caching I get the desired "update" message back. Any ideas what is wrong?

Thanks

The javascript running on the main page:

<script>
    window.onload = function longPoll(){
        var d = new Date;
        $.ajax({
            url: "http://localhost/site/update.php?time=" + d.getTime(),
            success: function(data){
                console.log(data);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                //error message here
            },
            type: "GET",
                            cache: false,
            complete: longPoll,
            timeout: 600000
        });
    }
</script>

The update script:

// while the file is NOT newer
while(!(filemtime('./test.txt') > $client_time)) {
    sleep(1);
}

echo 'update';
?>
Was it helpful?

Solution

Somthing to keep in mind:

1: never trust what you got from client side like time.

2: The time you send to the server with client side is not really what you except, so if the user time is set wrong like 11 jun and in server your current time is 10 jun, the

filemtime('./test.txt') > $client_time

always return false

3: use clearstatcache() when you check file status

4: sleep(1) is too high, specially when you want to deploy high usage website, change that to more than 10 ms

5: as vher2 said, use this code for complete:

complete: function(jqXHR, status) {
        if (status === 'success'){
            setTimeout(function(){ longPoll() }, 1000);
        }
}

Use this code to check current time on server and time time that received from user:

var_dump(time() , $client_time);

OTHER TIPS

Try this:

complete: function(jqXHR, status) {
        if (status === 'success'){
            setTimeout(function(){ longPoll() }, 1000);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top