Loading new data with Javascript/ajax based on server time and date - javascript

I currently have a JS ajax script to load data from the Database, where the query is in load.php
How would I make auto load new content separately based on the server time and date?
Such as rather than having the whole DB table refresh every "5 Seconds"
But loading the current data once, then new data based on server time/date.
Here is my script>
<script language="JavaScript">
window.onload = function()
{
$('#feed').empty();
$('#feed').load("load.php");
}
</script>

You cannot initiate sending AJAX data from the server without a request from the client (browser). So you should use the first request (the browser requesting the page itself) to calculate the time offset on the server (in PHP), and put your .load() function inside a setTimeout which will execute that many seconds later. So your PHP file would look something like this:
$time = 4300 // or whatever, based on your server clock.
echo '<script language="JavaScript">
window.onload = function(){
$("#feed").empty();
/* if you want to execute it once at page load too:*/
$("#feed").load("load.php");
/* then load after $time milliseconds:*/
setTimeout(function(){
$("#feed").load("load.php");
},'.$time.');
}
</script>';
Remember that setTimeout's offset is supposed to be in milliseconds.
Websockets are another solution to your problem if you have full server access (like to sockets and stuff). They involve basically creating a websocket connection when the script is first executed, and then server and client can send messages to each other as they please. These messages can include the data you wish.

Related

Real Time Refresh / Update

I have a MVC 3 project that publish in a server.
Scenario
For example I have a function for saving a data from (PC1) to (PC2).
It is possible that the viewing of data(data in jqgrid) in (PC2) is open(open in page) by a user and it will auto refresh or update the page or the jqgrid after the (PC1) save a data?
My jqgrid version is 4.3.3.
Hope you guys understand what I mean in my post. Post feedback if down votes. Thanks.
Any help will be accepted.
You might wonna use ajax to accomplish such a job, please read below
if I understand what you mean, is that you wonna poll a server to realtime updates on either intervals or something else...
option 1
Issue a normal stateless ajax call to the server, then force the server to hold the request for a limited time [to overcome server overhead]
This can also be reffered to as reverse ajax or comet.
Unless you are planning to use websocket technology, I hardly stress that you try this.
if(isset($_GET['finite'])){
#declare time for a session
$_SESSION['typing']=$reduce_browser_overhead=time();
#remember to close the session before entering the loop;
#if u dont close, then the browser will not reload the same website untill the connection is close or satisfied
session_write_close();
function loop(){
#do this to access external variables ===> $reduce_browser_overhead;
global $con,$reduce_browser_overhead;
#explicitly check 2exit
#please do this to release mysql connection since they are in a loop
if($reduce_browser_overhead+4<time()){
echo ' ';ob_flush();flush();
if(connection_aborted()){
#do some work here before you finally exit the connection
exit;
}$reduce_browser_overhead=time();
}
#php prepare statement...
$looper=$con->prepare("SELECT ROW FROM TABLE WHERE ID=SOMETHING AND $_SESSION[typing]=SOME_ROW");
#The statement above willcause the loop to work
#If a table had been update and table has not yet updated, this sql will detemin by the current time
#meaning that if the time[integer] of SOME_ROW is not equal to the time in the session variable,
#then it will let go to the client and then again it will continue looping untill the time in the
#SOME TABLE ROW changes....
$looper->execute();
$looper->store_result();
if($looper->num_rows>0){
sleep(2);
#do some work before looping again
loop();
#you have to explicitly return to this loop to work as expected.
return;
}else{
#send back data to the user or the client listening on the connection
session_start();$_SESSION['typing']=time();session_write_close();
#update the session before finishing the request so that the next time the request comes, the time will be equal to the DBserver time in the row and hence causing the loop again and again => more like a cycle
echo 'After some time the server has received new data which is =>> '.$newdata;
}
}loop();
exit;
//In another file on in the same document as the php / your server file ==> do javascript below
//first issue a normal / stateless ajax request to the target server
$.ajax({
//All optional but url required!
url:'abc.php?var_one=blabla',
cache:true,//whether to cache the requests
timeout:(1000*60)*20,//timeoutthe request
success:function(data){
//if the server successfully completed the request
//do some work here with data returned
},
error:function(){
//if the server return an error
//do more work around
//or call the function again
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Constantly read JSON database

I want to constantly read a JSON-formatted js file so my page shows the changes of that file.
I want some content in my page to change everytime I change the database file within the directory.
My files are:
objectoJSON.js:
var rightFencer;
rightFencer = {"name":"Jorge ANZOLA","nacionality":"VEN","points":10};
var leftFencer;
leftFencer = {"name":"John DOE","nacionality":"USA","points":5};
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<center><p id="rightFencerName"></p><p id="rightFencerPoints"></p> - <p id="leftFencerName"></p> <p id="leftFencerPoints"></p></center>
<script src="objetoJSON.js"></script>
<script>
document.getElementById("rightFencerName").innerHTML = rightFencer.name;
document.getElementById("leftFencerName").innerHTML = leftFencer.name;
document.getElementById("rightFencerPoints").innerHTML = rightFencer.points;
document.getElementById("leftFencerPoints").innerHTML = leftFencer.points;
</script>
</body>
</html>
I thought about putting those two scripts into an infinite while loop so by the time I change the file in the directory, it'd change. But it didn't work.
Also, I thought about using setInterval() to run the scripts every few seconds, but I didn't know how to make it work.
As you can see, I'm a complete noob, so ANY idea would be very appreciated.
Your "objectoJSON.js" is not a JSON file... it's a simple javascript object.
A JSON file would be something like this.
{
"rightFencer":{
"name":"Jorge ANZOLA",
"nacionality":"VEN",
"points":10
},
"leftFencer":{
"name":"John DOE",
"nacionality":"USA",
"points":5
}
}
What you are searching for is
Ajax, Server Sent Events or webSockets
Those update the pagecontent without the need to refresh the page or clicking something.
The following codes shows how to interact with each technology.
They have many advantages and disadvantages... to many to write right now.
ask specific and i can add that to the answer.
All the following examples are pure javascript and so don't need any type of library.They work with almost all new browsers... ios,android,windows also.
All the following examples could be adapted to work with a non properly formatted json file like that you posted. Look at the bottom.
Ajax:
Client asks for data
This updates the client every 30seconds.
function $(a){
return document.getElementById(a)
}
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function reloadData(){
ajax('database.js',updateText)
};
function updateText(){
var db=JSON.parse(this.response);
$("rightFencerName").innerHTML=db.rightFencer.name;
$("leftFencerName").innerHTML=db.leftFencer.name;
$("rightFencerPoints").innerHTML=db.rightFencer.points;
$("leftFencerPoints").innerHTML=db.leftFencer.points;
}
window.setInterval(reloadData,30000);//30 seconds
/*setinterval is a very bad way to update stuff ,
especially with ajax.. there are many other ways to do that.*/
Ajax does not need any type of server if you read the JS file locally.
Also appendding it... but both examples are time based... and that is not good if you have many users online. WS & SSE allow you to update each user individually depending on the necessity.
SSE:
Server sends data when needed
This uses php to create a Server Sent Events Server
Also this updates the client every 30 seconds, but in this case the server updates the client. Using Ajax the client asks the server to update.
The php file "sse.php"
header('Content-Type: text/event-stream'); // specific sse mimetype
header('Cache-Control: no-cache'); // no cache
while(true) {
if(/*something changes*/){
echo "id: ".time().PHP_EOL;
echo "data: ".$data.PHP_EOL;
echo PHP_EOL;
}
ob_flush(); // clear memory
flush(); // clear memory
sleep(30);// seconds
}
The javascript file
function $(a){
return document.getElementById(a)
}
function updateText(e){
var db=JSON.parse(e.data);
$("rightFencerName").innerHTML=db.rightFencer.name;
$("leftFencerName").innerHTML=db.leftFencer.name;
$("rightFencerPoints").innerHTML=db.rightFencer.points;
$("leftFencerPoints").innerHTML=db.leftFencer.points;
}
var sse=new EventSource("sse.php");
sse.onmessage=updateText;
WebSockets:
Server sends data when needed, Client asks for data when needed
webSockets is cool ... comunication is bidirectional. it is fast. but you need something like a nodejs server to be able to handle it properly.
function $(a){
return document.getElementById(a)
}
function updateText(e){
var db=JSON.parse(e.data);
$("rightFencerName").innerHTML=db.rightFencer.name;
$("leftFencerName").innerHTML=db.leftFencer.name;
$("rightFencerPoints").innerHTML=db.rightFencer.points;
$("leftFencerPoints").innerHTML=db.leftFencer.points;
}
var ws=new WebSocket('ws://YOURIP:YOURPORT');
/*ws.onopen=function(){ //those events are also aviable with sse
ws.send('WS open!');//sending data to the server
};
ws.onclose=function(){
console.log('WS closed!');
};*/
ws.onmessage=updateText;
Adapting the js
Ajax..
load the "objectoJSON.js" with ajax and evulate it ... but not using eval(). eval is evil. use new Function()
function updateText(){
document.getElementById("rightFencerName").innerHTML = rightFencer.name;
document.getElementById("leftFencerName").innerHTML = leftFencer.name;
document.getElementById("rightFencerPoints").innerHTML = rightFencer.points;
document.getElementById("leftFencerPoints").innerHTML = leftFencer.points;
}
(new Function(this.response+'\n updateText()'))();
or append the script every 30 seconds or whatever....
I don't write that example as it is the worst approach.
With 30 clients it means that you have to read the file from server evey second.
With SSE or WS you read it once and broadcast it to hundreds of clients.
I suggest to fix your json file.
if you have any other questions ask.
I guess you are working with framework which supports websockets.
You could listen for a change in file using websocket.it may return change in data set like new record or update on any record, or using javascript/ajax call get latest content from server and update your HTML.
https://www.websocket.org/demos.html, see foreign exchange dashboard to see how websockets can be used for constantly updating data.
The way you are doing it now isn't scalable, testable or manageable.
You really don't want to save data on the server using plaintext json files.
If you want a more robust framework for handling your use case, I suggest using web sockets on both the client side and server side (socket.io is a great choice), and using RethinkDB on your server as the DB.

Asynchronous API and callback

I have to use one asynchronous service. Everything I can do is send data to this service (I'm doing it with PHP and CURL) and send data to some url from this service. How can I react/wait for a response from this service?
Now I have two pages: first is sending data to service and the second takes a response from this service and inserts it to database. On a first page I'm checking some table while there isn't the response. But selecting from database few times per second is bad idea. But what I need to have: Send data from one page and get the response at the same page. I guess I can use some Ajax and make the async service sending data to the same page and wait for the response on this page.
I guess I wrote very hard because I can't fully explain what I need, so feel free to correct me.
As #Steve noted, PHP has no concept of asynchronousity. However there is a hack which allows to implement something similar to long-polling in PHP. The main point is to use a file ready to read in Javascript, i.e. JSON.
Here is a general flow:
Your single web page does AJAX request to your php script which send
appropriate request to the external service and immediately return
some response (e.g. empty) to the web page.
The web page starts to repeatedly request server for the same static
JSON file (by doing AJAX requests) until it appears (created by
callback script).
The external service passes response to your callback script which
save the response into the JSON file.
The web page get the response from the JSON file and outputs it.
Your easiest option is going to be ajax polling - send the request to the webservice, then poll every x seconds. The response handler (the script called by the webservice when it completes) need to save the data somewhere, eg database or session, and the poll script will check for this data.
Although this will add a little to server load, if you set the polling interval high enough it should be fine
session_start();
if(isset($_GET['sendrequest'])){
WebService:sendRequest(['callback_url'=>'thispage?receiveresponse=1'])
$_SESSION['response']=false;
die();
}elseif(isset($_GET['receiveresponse'])){
$response = WebService:receive();
$_SESSION['response'] = $response;
die();
}elseif(isset($_GET['checkresponse'])){
$data=[];
if($_SESSION['response']){
$data['success']=true;
$data['response']=$_SESSION['response'];
}else{
$data['success']=false;
}
header('Content-Type: application/json');
die(json_encode($data);
}
<html>
<head>....</head>
<body>
<a id="send" href="#">Send Request</a>
<div id="response"></div>
<script>
var poll;
$('#send').click(function(ev){
ev.preventDefault();
$post('?sendrequest=1', {...}, function(){
poll = setInterval(function(){
$get('?checkresponse=1', function(response){
if(response.success){
clearInterval(poll);
$('#response').html(response.response);
}
});
}), 3000);
});
});
</script>
</body>
</html>

making a loop with jquery, Ajax and PHP

i want to make a loop in jquery, Ajax and PHP.
my pages are:
shop.php
do_ajax.php
in the shop.php are variable $p_productid is 1 and $j_productid is $p_productid
var j_productid = <?= $p_productid ?>;
now i do j_productid++ so the output from $j_productid is 2
now i'm posting this with ajax to do_ajax.php
in the do_ajax.php are variable $pa_productid is $_POST['$j_productid'];
now i can place this on html, but i want to set this value in too the variable on $p_productid on shop.php
how i need to do this?
there is working a swipe system in this case so only with php it isnt working i need to work with jquery that's why am i doing this on this way. i got an another solution without AJAX but i want that you cant see on the client side the webpage is refreshing.
JQUERY
wipeLeft: function() {
var j_ProductId = <?= $g_ProductId ?>;
var j_Swiped = 1;
if (j_ProductId < <?= $l_LastProduct ?>){
j_ProductId++
//document.swiping.productid.value = j_ProductId;
//document.swiping.submit();
$.ajax({
url: 'do_ajax.php',
type: 'POST',
data: { swipe : j_Swiped,
productid : j_ProductId},
success: function (data) {
$('.product').html(data);
}
});
}
}
do_ajax.php
if(!empty($_POST['swipe'])){
$l_ProductId = $_POST['productid'];
echo $l_ProductId;
}
You need to understand that the JavaScript (even if generated dynamically by PHP) is not running the same time that PHP is running. Your workflow will be something like this:
PHP script (shop.php) is invoked
PHP script generates output, HTML and JS mixed.
These are all in server side until the web server sends the output to client (browser)
In browser HTML displays and JS runs with starting values that you generated previously by PHP. But in this time, PHP has been finished, not running anymore. PHP variables are not alive anymore.
JS interacts with the user in browser, we can say it's running continuously.
Triggered by an action (swipe) JS sends an (ajax) request from client side to server side. This request transfers the new value to server side, and invokes another PHP script (do_ajax.php). You do whatever you want with the new value (process it and or store it) in server side. You need to understand that you are in a completely disjunct scope in PHP than in your first PHP script. (distinct in time too)
If you want to be sure that, in case of a page reload, the (product ID) value will be the updated value, you need to store it somewhere (user session, key-value store, database, or any persistent) when you get it in server side (so in do_ajax.php) and later load this value in the beginning of your shop.php script ...which will pass it to the JS, and so on. The workflow starts again.

setInterval php variable in javascript [duplicate]

This question already has an answer here:
PHP code only runs once inside javascript setInterval
(1 answer)
Closed 8 years ago.
I am trying to post an updating ping on my website, without having it reloading all the time, yet when i try it posts the initial ping, but it doesnt update after the time interval i've set
index.php :
<script>
setInterval(document.write('<?php echo json_encode(getPingout());?>'),100);
</script>
functions.php :
<?php
function getPingout() {
// some function that finds the ping of the server
return $server->getPing();
}
?>
You can't just have php run multiple times after a page has loaded. That PHP is executed one time when the page loads.
To do what you are attempting to do you should use some javascript and an ajax call.
$(function(){
function pingServer(){
$.post('/ping.php',function(data){
console.log('server is ok');
});
}
setInterval( pingServer, 4000 );
});
Also you may not need to ping the server every that often (every 100). Otherwise you may have issues.
That is not how javascript & PHP work together.
In order to refresh data without a page reload, you must request the data asynchronously. Search for AJAX or XHR, I really recommend that you look into something like jQuery though, as you will save alot of time writing code and debugging, compared to if you were to write the javascript by yourself.
If you were to do this in jQuery:
//this means run when page is ready
$(function(){
setInterval(function(){
//Send POST request to ping.php
$.post('ping.php',{},function(){
//Append the result to the body in a new div
$('body').append($('<div>'+data+'</div>'));
});
},100);
});
and your ping.php should simply return the ping and nothing else.
And don't let the dollarsigns confuse you, in PHP its a prefix for variables, but in the javascript/jquery context it simply is a variable, containing the jquery object that you call functions from.

Categories

Resources