The difference between regular ajax and long polling

I’m trying to understand more about the lengthy survey in order to “manipulate” the website in real time, I saw several videos, and now I’m thinking:

Say I have an old date that sql and I am echoing on it. Since a long poll will know if the old date will not be what it will look from time to time according to the setInterval ... function?

Let's say I want to show the publication of a blog in which all the text is in mysql, but repende I am publishing a new publication, and who is on the page at that time, you will see the publication time (do not tell me?), Then how one long poll code will know difference between old and new publication? Ate did not even allow to contradict or repeat the same date engraved on sql.

+4
source share
1 answer

Since your initial question was what is the difference between the two methods, I will start with this:

AJAX poll

Using an AJAX poll to refresh the page means that you send a request at a certain interval to the server, which will look like this:

AJAX polling

The client immediately sends a request to the server and server responses.

A simple example (using jQuery) would look like this:

setInterval(function(){
    $('#myCurrentMoney').load('getCurrentMoney.php');
}, 30000);

The problem is that this will cause a lot of useless requests, because with each request there will not always be new things.

AJAX Long Survey

Using a long AJAX poll will mean that the client sends a request to the server, and the server waits for new data that will be available before it is answered. It will look like this:

Ajax long polling

, "". , .

:

refresh = function() {
    $('#myCurrentMoney').load('getCurrentMoney.php',function(){
        refresh();
    });
}

$(function(){
    refresh();
});

, getCurrentMoney.php , , .

. , , : , " " indiactor:

<?
$time = time();

while ($newestPost <= $time) {
    // note that this will not count as execution time on linux and you won't run into the 30 seconds timeout - if you wan't to be save you can use a for loop instead of the while
    sleep(10000);
    // getLatestPostTimestamp() should do a SELECT in your DB and get the timestamp of the latest post
    $newestPost = getLatestPostTimestamp();
}

// output whatever you wan't to give back to the client
echo "There are new posts available";

"" .

+4

All Articles