convert AJAX short polling to long polling [duplicate] - javascript

I'm trying to understand more about long polling to "manipulate" a website in real time, saw some videos and I'm thinking so far:
Say I have an old date that the sql and I make an echo on it. As long polling will know if the old date will not be the same as it will look from time to time according to the setInterval function ...?
Say I want to show publication of a blog in which all text is in mysql, but repende I publish a new publication, and who is on the page at the time, you will see the publication time (not tell me?), Then how one long polling code will know the difference between the old and the new publication? Ate even not to give conflicting or repeating the same date engraved on the sql.

Since your initial question was what the difference between the two techniques is, I will start with this:
AJAX polling
Using AJAX polling to update a page will mean, that you send a request in a defined interval to the server, which would look like this:
The client sends a request to the server and the server responses immediately.
A simple example (using jQuery) would look like this:
setInterval(function(){
$('#myCurrentMoney').load('getCurrentMoney.php');
}, 30000);
The problem with this is, that this will cause a lot of useless requests since there won't be always new things on every request.
AJAX long polling
Using AJAX long polling will mean, that the client sends a request to the server and the server waits for new data to be available before he responds. This would look like this:
The client sends a request and the server responds "irregularly". As soon as the server responds, the client will send a new request to the server.
The client side would look like this:
refresh = function() {
$('#myCurrentMoney').load('getCurrentMoney.php',function(){
refresh();
});
}
$(function(){
refresh();
});
What this will do is just load the getCurrentMoney.php's output into the current money element and as soon as there is a callback, start a new request.
On the server side you usually use a loop. To solve your question how the server will know, which are new publications: either you pass the timestamp of the newest to the client available publication to the server or you use the time of the "long polling start" as 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";
Here we won't have "useless" requests.

Related

Difference between client and server time

I want to use server time in an php/javascript application. Time to the second is quite important for the app. However there appear to be some discrepancies of up to 3-4 seconds, despite checking the time differences between client and server time.
My angular code is as follows;
// Pre ajax time (so we can see how long it took to get data from server)
var timeElapsed = new Date().getTime();
$http.get('/getServerTime.php')
.success(function (data) {
// Calculate the length of the ajax request in seconds
timeElapsed = new Date().getTime() - timeElapsed;
// Add that to the returned server time to get the current
// server time. (data.date is provided by the getServerTime.php page)
$scope.serverTime = data.date + timeElapsed;
$scope.timeDifference = new Date().getTime() - $scope.serverTime;
});
Theoretically this should work but discrepancies of up to four seconds are occurring.
Any suggestions or code modifications would be gratefully received.
Its not a good idea to mix client and server time at all.
Client time is not reliable at all, since the user can change his time anytime and anyhow he wants. If he feels funny he can make his time 06.06.2066 right now. What would your program do then ? Probably nothing good.
Do not mix these up and the best way would probably be to use the server time -only-
Except you just need the difference of two time points to evaluate a duration. In this case you can use the client-time since for a difference of timestamps the absolute value doesn't matter (2016 or 2066, who cares... 3 seconds are 3 seconds)
Furthermore there is another problem in your code. If you want to "calculate the current server time" by adding the value returned from the server plus the time elapsed since your ajax call - you're missing the delay your request takes to reach the server.
say you send your request at 0ms - the server will get the request at 20ms and put it's current server-time in the response. then your client will get the result at, say, 50ms.
then the calculated server time will be off by 20ms compared to the actual server time.
in the end what you're trying to do seems like a very non-best-practice approach to be fair.
Maybe if you tell us what exactly you want to achieve with this approach we can help you find a better solution
You can configure your server to return it's time in a "Date" header - this is a standard http header - this way you don't need to have a dedicated rest for it:
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Even so you will only have the timestamp when the request left the server.
If you have the same problem as me and you need to display the time passed since something started on server - the network latency is not much of an issue here.
For any other usages you will need to let UTC do the work.
Hope it helps.

Send local Javascript date to server on first access

Is there a way to read the user's date when first requesting a page to the server? I'm puzzled on how to sync server time and client time, and maybe sending the client time to the server would be a good solution.
I'm currently doing the inverse, outputting the server time on the page, so JS will read it, but I need to actually read the user's time and then process data on the server based on it.
The only way I can do it until now is loading the page then using an ajax call to send the time.
From the client side, you can execute an XmlHttpRequest to the server using jQuery:
$(function() {
var userTime = new Date();
$.post("path/to/record.php", {"userTime": userTime}, function(data) {
// do something with data, if necessary...
});
});
On the server, you can log the information however you feel fit:
<?php
if(!empty($_POST['userTime'])) {
$userTime = $_POST['userTime'];
// do something with it.
}
?>

Send data to client page from mysql database without refreshing page (timeout)

I created a tabulation system for beauty pageants that show judges score on a projector. I created a presentation page for that using Codeigniter.
The HTML from that presentation page is purely written in Javascript. The page refreshes each second to get real-time data sent by the judges.
The not-so-cool thing about this logic is that when the page writes a lot of data, the page blinks every second. So the refreshing of the page is noticeable and somewhat disturbing.
This is a snippet of the code I'm working on.
$(document).ready(function() {
getJudgesScore();
setInterval(function(){
if (getNumFinalists() == 0)
getJudgesScore();
else {
window.open ('presentationFinalists','_self',false)
}
},1000);
});
You can imagine how much data is being sent and received every time this code is executed.
To sum this up, what I want to accomplish is instead of the client asking for data every second, the server initiates the connection every time a new data is saved to the database. Thank you for taking your time reading my concern.
This might help you to take necessary data from mysql server and send to client page.
Timer jquery run for after perticular time of interval.
<script src="../JS/Timer/jquery.timer.js"></script>
var timer = $u.timer(function() {
getJudgesScore();
});
timer.set({time: 1000, autostart: true});
refer this link also
https://code.google.com/p/jquery-timer/source/browse/trunk/jquery.timer.js?r=12
What you are attempting is a tricky -- but not impossible -- proposition.
#Chelsea is right -- the server can't genuinely initiate a connection to the client -- but there are several technologies that can emulate that functionality, using client connections that are held open for future events.
Those that come to mind are EventSource, Web Sockets, and long polling... all of which have various advantages and disadvantages. There's not one "correct" answer, but Google (and Stack Overflow) are your friends.
Of course, by "server," above, I'm referring to the web server, not the database. The web server would need to notify the appropriate clients of data changes as it posts them to the database.
To get real-time notification of events from the MySQL server itself (delivered to the web server) is also possible, but requires access to and decoding of the replication event stream, which is a complicated proposition. The discovered events would then need to result in an action by the web server to notify the listening clients over the already-established connections using one of the mechanisms above.
You could also continue to poll the server from the browser, but use only exchange enough data via ajax to update what you need. If you included some kind of indicator in your refresh requests, such as a timestamp you received in the prior update, or some kind of monotonic global version ID such as the MySQL UUID_SHORT() function generates, you could send a very lightweight 204 No Content response to the client, indicating that the browser did not need to update anything.

XMLHttpRequest is timeout before response is arrived

I am calling one cgi script which takes 50 minutes to send response.I need to keep my xhr alive till the response comes from that cgi.
How to do that ?
it seems like after certain default time request automatically timed out.
You can use:
xhr.timeout = 10000;
xhr.ontimeout = timeoutFired;
for this purpose
I don't think you should be doing this inline with the request. The alternative is to submit your request as a job to some back end process/thread/message queue and store a reference so that you can access the results, e.g. in a database or even a file once the processing is complete.
Until the results are available, you could show some 'updating' text or spinning icon to let the user know something is happening.
For that length of time I wouldn't rely on an open HTTP connection.

How to make Ajax requests each 10 seconds (besides long-polling)?

I'm trying to get request a json object from the server each 10 seconds using this:
setInterval(function(){
$.ajax({
url: '/',
success: function(data){
//do stuff with data
}
});
}, 10000);
But this isn't very efficient. I know about long-polling, but I don't think it'll make a big difference. I know I will receive new data each 10 seconds, so doesn't that make long-polling the exactly same as setInterval in terms of efficiency?
Is browser-side caching a good solution for this problem?
The JSON object I'll be getting looks like this:
var data = {1: {'user': 'John', 'age': '25'}, {2: {'user': 'Doe', 'age': '30'}}
With this, I want to display data[0].user for a few seconds and after that smoothly change it into data[1].user by using 'fadeOut' and 'fadeIn' and so on until it runs out of users.
I basically want to create a slideshow of the user's usernames.
Would caching be a good solution or should I stick with making ajax calls every 10 seconds? If so, then how would I implement this and if not, what method should I use?
I'm not sure if i explained it good enough, so tell me if something is still unclear.
I would definitely think about caching. Especially if you get sets with a lot more users, making an AJAX request every 10 seconds could easily overload your server. However, if you want to keep it simple, make a request every few minutes instead, to update. Cache the users, have them generated into the javascript code, say users = new Array(user1, user2, ...). You don't really have to keep updating the page if it's not that important, as most users would navigate away within a minute or two anyways. If you have a long list that changes every few seconds, that gives you enough time to not ever have to update using AJAX, and just rely on the server generated list of users.
If not, store the last time you updated the list in a variable, and send the time as an argument to your server when you're updating via AJAX, and then have the server quickly check what new users were added, and send just those. Then, just merge the new array of new servers with the old array. I highly suggest not making a call every 10 seconds for a new name though. Not only will you run up more bandwidth on your server, you will increase the CPU usage when it has to find the next user in the list for you, and then send you that one. For good practice, always let the client do as much of the work as possible, without having lag. There is only one server, but many more clients. Each operation you shift to the clients will save your server hundreds, if not thousands, of operations.
As for long polling vs setInterval, I would recommend setInterval in that case. You can at least send a request with a time argument, specifying the last update time, and thus only needing to send that small portion, instead of the entire data array.
var storage = new Array(user1, user2, ...); //set all your data here, generate it from your server
var lastUpdate = //set the last time you updated it, just create a date variable
function rotateUsers()
{
//do your fade in and fade out here
}
function update()
{
//create a new HttpRequest, and then set the url as "yoursite.com/update?lastUpdateTime="+lastUpdate;
//Take the response data, and merge the new users list with the old one
}
setInterval('rotateUsers()',10000);
setInterval('update()',60000); //update once a minute
Long polling would be better than setInterval(fn,delay) because at least then the server would just send you updated data when it was ready, versus the client making that assumption and then firing off a request for data that may not have changed.
If you have control over client/server tech, you can push data to the client without the need to reconnect the XHR on each push by using WebSockets

Categories

Resources