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
Related
My main goal here is to execute a python script I have written when I run a function triggered through HTML. Here is how I have things currently set up:
I have a JavaScript File containing python run functions:
const PythonShell = require('python-shell').PythonShell;
class AHK {
static async runScript() {
PythonShell.run('/ahk/script.py', null, function (err) {
if (err) throw err;
console.log('finished');
});
}
module.exports = AHK;
I have my main.js file which would be the js code for the HTML to handle. I'd like for it to take in the module AHK. Something simple like this:
const AHK = require('./ahk');
function runFunction(x){
if(x = 1)
AHK.runScript()
}
And then I have some HTML with a javascript tag
<script type="text/javascript">
let x =1; //this is just to show x is getting populated. In the actual code it's constantly changing values
async function predict() {
if(x > 1)
runFunction(x)
}
</script>
Biggest issue I'm facing:
I've become aware that browser javascript doesn't like requirements/modules. For example, the main.js file doesn't like having a requirement at the top. I've tried using things like requirejs, but I can't seem to figure out how to make something like this work. I basically need it so that when the requirement is met and the function runFunction is run, the python script is executed on my machine.
Important to note that this is all running for a personal project on my computer, so it will never not be local.
Make the application on your pc an API and use the web page to send a request to the API telling it which python script to run. I haven't used python too much but I believe you can make an API with it. Then you can just make buttons for each python program you want to run and have these buttons send a request to the API.
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 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);
I am trying to get the HTML (ie what you see initially when the page completes loading) for some web-page URI. Stripping out all error checking and assuming static HTML, it's a single line of code:
function GetDisplayedHTML($uri) {
return file_get_contents($uri);
}
This works fine for static HTML, and is easy to extend by simple parsing, if the page has static file dependencies/references. So tags like <script src="XXX">, <a href="XXX">, <img src="XXX">, and CSS, can also be detected and the dependencies returned in an array, if they matter.
But what about web pages where the HTML is dynamically created using events/AJAX? For example suppose the HTML for the web page is just a brief AJAX-based or OnLoad script that builds the visible web page? Then parsing alone won't work.
I guess what I need is a way from within PHP, to open and render the http response (ie the HTML we get at first) via some javascript engine or browser, and once it 'stabilises', capture the HTML (or static DOM?) that's now present, which will be what the user's actually seeing.
Since such a webpage could continually change itself, I'd have to define "stable" (OnLoad or after X seconds?). I also don't need to capture any timer or async event states (ie "things set in motion that might cause web page updates at some future time"). I only need enough of the DOM to represent the static appearance the user could see, at that time.
What would I need to do, to achieve this programmatically in PHP?
To render page with JS you need to use some browser. PhantomJS was created for tasks like this. Here is simple script to run with Phantom:
var webPage = require('webpage');
var page = webPage.create();
var system = require('system');
var args = system.args;
if (args.length === 1) {
console.log('First argument must be page URL!');
} else {
page.open(args[1], function (status) {
window.setTimeout(function () { //Wait for scripts to run
var content = page.content;
console.log(content);
phantom.exit();
}, 500);
});
}
It returns resulting HTML to console output.
You can run it from console like this:
./phantomjs.exe render.js http://yandex.ru
Or you can use PHP to run it:
<?php
$path = dirname(__FILE__);
$html = shell_exec($path . DIRECTORY_SEPARATOR . 'phantomjs.exe render.js http://phantomjs.org/');
echo htmlspecialchars($html);
My PHP code assumes that PhantomJS executable is in the same directory as PHP script.
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.