I have the following script at the bottom of my php page, it runs on pageload, but I need it running every 10 seconds. It only runs on page load.
PHP is running.
I've tested this with a countdown from ten, and the script is actually looping, but for some reason not when i integrate this PHP.
Please help.
<script>
var CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";
var x = setInterval(function () {
CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";
document.getElementById("CurrentTestBranch").innerHTML = CurrentBranch;
CurrentBranch = "";
}, 10000);
</script>
Edit:
The code does display the file contents the first time around. But does not refresh when I make a change and save it.
Your PHP code is run only when the page loads. It generates string literals when it runs. These do not get updated when the interval function gets called repeatedly (because the PHP does not run again).
If you want to get new data from PHP you need to make new HTTP requests.
You could either reload the entire page, or use XMLHttpRequest (or fetch) to call a web service that gives you the data you want (Ajax is a useful search term).
PHP happens before HTML hits the server.
Look up setTimeout() javascript command. What you need to do is get javascript to call another php script, which checks and echoes your value.
Something like this (could be pseudocode, from memory):
setTimeout(function(){
var CurrentBranch = $.get('/url/that/sends/value');
// do something with your value, call a function, whatever
}, 10000);
Related
I'm trying to make a website load forever. My current idea is to request a PHP file:
<?php
sleep(30);
This will delay the load by 30 seconds, which a quick Google search tells me should be within most browsers' timeouts. I was thinking of writing some JavaScript to append a new link tag after a bit less than 30 seconds to keep the page loading, but I found that this didn't keep the loading icon spinning (with Chrome at least):
window.addEventListener( 'load', () => {
var i = 0;
setInterval( () => {
i++;
var newScript = document.createElement('script');
newScript.src = 'infinite-loading.php?i=' + i;
document.querySelector('#infinite-loading').after(newScript);
console.log('The deed is done');
}, 25000)
} )
<script id="infinite-loading" src="infinite-loading.php"></script>
The code above appends a script tag every 25 seconds, and the browser loads the PHP file each time, but it doesn't show the loading icon. I added the URL parameter because I wasn't sure if browsers would cache the page.
I also want to make sure that the server with the PHP file won't be overloaded. I'm not sure if many sleep() functions running constantly at the same time will cause any issues.
Is there a better way to do this client-side? Should I use something other than PHP? Something multi-threaded?
(Edit: Sorry for the awkward title, Stack Overflow didn't like my first one.)
You need that browser will continue reading your page forever (I'm talking about HTML, not other linked objects). So you need not to break timeout and feed some data from backend to frontend.
Example of sending portion of data to client:
ob_end_flush();
# CODE THAT NEEDS IMMEDIATE FLUSHING
ob_start();
Now we need to understand the minimum data packet size that is expected by the browser. Minimal googling tells us a limit of 8-10 bytes.
So combining this together we can try to check (I did not checked, it is just my version):
<?php
while (true) {
sleep(25);
ob_end_flush();
echo " "; // 10 spaces...
ob_start();
}
Not sure why you would want to do anything like this but the simplest solution I think is an endless loop.
<?php
while(true)
{
}
I've been banging my head against the wall trying to get a JavaScript equivalent to this php snippet:
<?php
$id = 'uniqueID'
$now = round(time()/60);
$lock = md5($now . $id);
?>
I've been trying variations on this:
var timeInMin = new Date().getTime() / 60000;
var timestamp = Math.round(timeInMin);
var key = md5(timestamp + 'uniqueID');
utilizing an md5 script from here
I merely need lock and key to match. Seems simple to me. What am I doing wrong?
As said before me, if time not matching it will not create the same hash. What I do in situations like that is to find way to pass the time from php to the client side so they can use the same exact time.
PHP side:
<?php
$id = 'uniqueID';
$now = round(time()/60);
$lock = md5($now . $id);
print $lock;
setcookie("time",$now);
?>
Client Side:
<script type="text/javascript">
var timestamp = getCookie("time");
var key = md5(timestamp + 'uniqueID');
console.log(key);
</script>
Note that getCookie is a shortcut function
The following example is here to present the idea in a simple form. I would not use time as the name of the cookie nor give access to the vars (wrap in function). Uglify scripts goes a long way in cases like this.
To put it in concrete terms (my comment was slightly facetious):
PHP is a server-side language. When your browser fires a request for a page over the internet (or even to a listening port on your local machine), the instance of apache running on the server (or your local machine) executes the PHP on the page, then spits it back out to the browser.
The browser then executes any JavaScript on the page, we refer to this as client-side.
Because you are using Math.round, if it takes more than 30 seconds between the time your server executes the PHP (server-side) and the time your browser starts executing the relevant Javascript (client-side) then the time in minutes will be different. Using Math.floor instead would give you 59 seconds of wiggle room but that's still dicey, especially on mobile.
Even assuming the page executes the JavaScript immediately after loading and loads pretty quickly 30 seconds of latency is not totally off the table, and on mobile neither is 59.
I was wondering if there's a method to force a URL page to refresh on command using JS that's on the same server.
Ex: I have a URL page that's open on three devices on the same server. When I click update, the URL will automatically refresh on all three devices?
I can only figure out how to fresh it if it's on the same device right now.
CODE IN MY PHP FILE:
function refresh() {
setTimeout(function () {
location.reload(true)
}, 100);
}
CODE IN MY HTML:
button onclick="updateData(); refresh()">Update</button>
You should set ajax data retrieve task on every set seconds.(loop script)
If Ajax script found there is your command to reload, take the task.
Eg:get data from reload.txt
do nothing on get value is 0, And your action make the txt to 1.
If ajax script found it is 1, do reload by the script.
1 - Create reload.txt beside your page.php and write only 0 in txt.
In your php file write this script inside html part -
<script>
function load(){
$.ajax({
url : "reload.txt",
dataType: "text",
success : function (data) {
if (data == 0) {
$(".text").html(data); // to check number and not necessary for your function
}
else{
window.top.location = "/";
<?php $file = fopen("reload.txt","w");
fwrite($file,"0");
fclose($file); ?>
}
}
});
}
load(); // This will run on page load
setInterval(function(){
load() // this will run after every 5 seconds
}, 5000);
</script>
<div class="text">will appear here</div> // to check number and not necessary for your function
For complete function you need to set it 0 on page reload.
And Finally add function to change txt value to be 1 in your server reload button and test it.
PS: You should innovate your function than 0/1 method. just like incremental or something and store it in $_SESSION to work for all of clients.
i've wrote a script in which javascript file and innerHTML refreshes time to time
setInterval(activeload,1000);
function activeload() {
activediv.innerHTML="";
scriptsrc.src="http://localhost/mypro/pro/activeuser.php";
for(i=0;i<=activeuser.length;i++) {
if(activeuser[i]!=null)
activediv.innerHTML+="<p onclick='dial(' " + activeuser[i] +" ' )'> " + activeuser[i] +"</p><br>";
}
scriptsrc.src='';
}
in the above script, innerHTML is modifying, but src attribute of script is not changing...
the js file loaded is
<script src="http://localhost/mypro/pro/activeuser.php" id="scriptsrc" type="application/javascript"></script>
this php file refreshes every 5 secs and is accurate in information.
need some help in loading the javascript perfectly
Although it's not clear to me what you want to do with the array that comes from activeuser.php, it seems like AJAX will be your best bet to bring it in to your page on a regular interval. Here is a basic example of an AJAX call using jQuery:
<script src="jquery-2.1.4.min.js"></script>
<script>
setInterval(function() {
$.ajax("/mypro/pro/activeuser.php").done(function(data) {
console.log(data);
});
}, 5000);
</script>
The way it works is that the $.ajax() call will request activeuser.php from the server. As soon as the file is delivered, the anonymous function inside of .done() will be called. That function has one parameter, which I've named data, that contains the contents of activeuser.php.
AJAX is a very convenient way to request data from the server without reloading the entire current page when the data is delivered to the browser.
I'm currently programming in JSP and Javascript. (I am by no means an expert in either). Right now, what I want is for a Javascript function to be called repeatedly and one of the variables to be queried from the database repeatedly (it is the date that the page was last modified). If this variable is greater than when the page was loaded, I want the page to refresh.
What I have so far:
...
<body onload="Javascript:refreshMethod()">
<script type="text/JavaScript">
<!--
function refreshMethod()
{
var interval = setInterval("timedRefresh()", 10000);
}
function timedRefresh() {
var currenttime = '<%=currentTime%>';
var feedlastmodified = '<%=EventManager.getFeedLastModified(eventID)%>';
var currenttimeint = parseInt(currenttime);
var feedlastmodifiedint = parseInt(feedlastmodified);
if(feedlastmodifiedint > currenttimeint)
{
alert(feedlastmodifiedint);
setTimeout("location.reload(true);",timeoutPeriod);
}
if(feedlastmodifiedint < currenttimeint)
{
alert(feedlastmodifiedint + " : " + currenttimeint);
}
}
// -->
</script>
The problem is that everytime the timedRefresh runs, the feedlastModifiedInt never changes (even if it has been changed).
Any help would be appreciated,
Thanks.
The JSP code within the <% ... %> tags runs only once, on the server-side, when the page is loaded. If you look at the source of the page in the browser, you will find that these values have already been placed within the JavaScript code, and thus they will not change during each timer interval.
To update the data as you are expecting, you can use AJAX. You can find plenty of tutorials online.
JSP and JavaScript doesn't run in sync as you seem to expect from the coding. JSP runs at webserver, produces a bunch of characters which should continue as HTML/CSS/JS and the webserver sends it as a HTTP response to the webbrowser as response to a HTTP request initiated by the webbrowser. Finally HTML/CSS/JS runs at the webbrowser.
If you rightclick the page in webbrowser and choose View Source, you'll probably understand what I mean. There's no single line of Java/JSP code. It has already done its job of generating the HTML/CSS/JS. The only communication way between Java/JSP and JavaScript is HTTP.
You need to move this job to some servlet in the server side and let JS invoke this asynchronously ("in the background"). This is also known as "Ajax". Here's a kickoff example with a little help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
var refreshInterval = setInterval(function() {
$.getJSON('refreshServlet', function(refresh) {
if (refresh) {
clearInterval(refreshInterval);
location.reload(true);
}
});
}, 10000);
});
</script>
Where the doGet() method of the servlet which is mapped on an url-pattern of /refreshServlet roughly look like this:
response.setContentType("application/json");
if (EventManager.getFeedLastModified(eventID) > currentTime) {
response.getWriter().write("true");
} else {
response.getWriter().write("false");
}
See also:
Communication between Java/JSP/JSF and JavaScript