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.
}
?>
Related
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.
I am currently developing a C# application that pulls information from a specific program. The information is pulled and updated about once every second. I want to export the information to a locally stored website (with HTML, CSS, and JS), and have it updated constantly without any need of refreshing the page.
Is there any way to do this?
The information stored will be in a string format, if it helps.
You will need to have a server read in the data and serve it on some path. The client webpage can make AJAX requests at timed intervals to get the data from the server.
If you have a domain name like http://example.com and you serve the data from /dataPath, then the client-side javascript that pulls data from the server every second could look something like this:
(function timedFunction () {
setTimeout(function getData () {
fetch('http://example.com/dataPath')
.then(function(response) {
// Do something with data
});
timedFunction();
}, 1000);
})();
var k=new Date();
alert(k);
It alert local time. But I need to display current server UTC time.
JavaScript is basically on client side. You will not be able to get server time in java script as it will be executed on client and give you the server time only (Node.js is exception here).
If you really wish to have server time in javascript. You can write a Api or Webservice on serverside which will give you server time in format you want. Call this webservice/Api using XMLHTTP or Ajax request and parse the response and display the time as per your wish.
Ajax post Code Example :
$.post( "Your Web Service Page", function( data ) {
//Assuming that Your web service will not need any paramerter
and just write the server time in utc in response
alert(data );
});
Try this new Date().toUTCString()
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.
I'm trying my hand at unobtrusive JS, using JQuery in my Ruby On Rails app.
After the user fills out a form, the client-side JQuery code calls:
$.post("/premises", ui.form)
I can see the POST hit the server, and I can see the server emit a redirect notice to http://localhost:3000/users/42 complete with the data to be displayed.
But the browser page doesn't change. This doesn't really surprise me -- the whole point of client-side javascript is to control what gets updated -- I get that. But in this case, I'd like to honor whatever the server replies with.
I tried extending the call to post() based on How to manage a redirect request after a jQuery Ajax call:
$.post("/premises",
ui.item,
function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
} else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
});
... but (among other problems) data.redirect is undefined. I suspect the real answer is simple, right? Looking forward to it!
The post you refer to uses JSON as return value and it is constructing that json on server side. it means if there is redirect your data object would look like
{redirect:'redirecturl.html'}
and if it is not redirect then data object would be like
{form:html-string-for-form}
now job is to construct json object accordingly on server side
The server is saying that the data you want to process with JavaScript is available at a different URL, not that the browser should load a new document into the top level frame. Sending the browser to the URL where it was told the data it was requesting with JS is wouldn't be honouring the redirect.
If you want to do that, then the server should respond with data (in the body of the response) that the JavaScript interprets as a reason to assign a new value to location.
data.redirect is probably undefined because you're not specifying it on the server side. In the answer you linked to the point was to have the server always respond with 200 regardless of the outcome, and then the JSON body it sends back determines how the client reacts. So, on the server side you'd want to respond with {"redirect" : "/where/to/go"}