how to check if content txt file has changed - javascript

Situation:
I am reading the content of a .txt file with php and with AJAX i load the content into a div. The javascript checks every 5 seconds the .txt file and put the content into the div.
If the content of the .txt file changes, (which i do with a form submit), the content of the div changes automatically after 5 seconds.
For this; i use a checkbox with 3 options:
Status: Available
Status: Busy
Status: Paused
One of the 3 lines above is in the .txt file.
Situation now: every 5 seconds check of the .txt file and every 5 seconds refresh of the div. Is it possible that if the content of the .txt file has not changed, to keep the refresh away?
How can i achieve this?
Below the javascript:
function Ajax()
{
var
$http,
$self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 5000);
}
};
$http.open('GET', 'loadtxt.php' + '?' + new Date().getTime(), true);
$http.send(null);
}
}
Loadtxt.php
<?php
//
$file = "status.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 5000) ) {
echo $line;
}
?>
The div:
<script type="text/javascript">
setTimeout(function() {Ajax();}, 5000);
</script>
<div id="ReloadThis">Default text</div>

Calculate the HASH of the file on the server-side have your AJAX check with the for the hash (say a SHA1 or an MD5) - and only update the DIV if the hash has changed since it last looked ?
Maybe this PHP function on the server could help here ?
string hash_file ( string $algo , string $filename [, bool $raw_output = false ] )
Which I found on this link : http://php.net/manual/en/function.hash-file.php
So something like this (I am not in a position to test this; so edits are very welcome here):
filehash.php:
<?php
$file = "status.txt";
echo hash_file( "SHA1", $file, $raw_output=false )
?>
Set up a Javascript variable like 'fileHash':
var fileHash;
populate with an AJAX call to the new PHP script:
[...]
$http.open('GET', 'filehash.php' , true);
newFileHash=$http.responseText;
if (fileHash!=newFileHash) { // file changed - so fetch contents
[...]
// check me here: can we just make use of $http twice here ?
$http.open('GET', 'loadtxt.php' + '?' + new Date().getTime(), true);
// update div.
document.getElementById('ReloadThis').innerHTML =$http.responseText;
fileHash=newFileHash;
}
setTimeout(function(){$self();}, 5000);
[...]
Alternative suggestion:
Your webserver might be able to automatically return a HTTP code to state that the file hasn't changed since it was last requested (by comparing with your browser headers) - with an HTTP 304 for instance:
From Wikipedia:
304 Not Modified
Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or
If-None-Match. This means that there is no need to retransmit the
resource, since the client still has a previously-downloaded copy.
It looks like you have added a timestamp parameter to your GET request - which I presume is prevent your browser caching the old copy of the text file: if you do opt for the method above, you should remove this from your GET request - as this will appear to the webserver that you are asking for a new document each time.

Related

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

how do you connect an ajax post to a specific conditional in PHP file?

So i have written a function that is called onclick in my html file that uses AJAX, but i would like for this post to go to a specific table in mysql.
$('#submitIFC').click(function(e) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var opinionIFC = $('ul.sort').sortable('toArray').join(',');
request.onreadystatechange = function() {
if ((request.readyState===4) &&(request.status===200)) {
var return_data = request.responseText;
document.getElementById('rank_ul').innerHTML= 'return_data';
// Preventing the default action triggered by clicking on the link
e.preventDefault();
e.preventDefault();
}//end of if
}//end of onreadystatechange function
//send requested movie to php file which will send to the external server
request.open("POST", "results.php", true);
request.send(opinionIFC);
document.getElementById('rank_ul').innerHTML='<img src="ajax-loader.gif">';
});
however there seems to be an issue with connecting this to my php if conditional, i tried copying the contents on my request.send(), like so
if($_POST['opinionIFC'])
{echo
// The data arrives as a comma-separated string,
// so we extract each post ids:
$data=explode(',',str_replace('li','',$_POST['sortdata']));
// Getting the number of objects
list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));
if(count($data)!=$tot_objects) die("Wrong data!");
foreach($data as $k=>$v)
{
// Building the sql query:
$str[]='('.(int)$v.','.($tot_objects-$k).')';
}
$str = 'VALUES'.join(',',$str);
// This will limit voting to once a day per IP:
mysql_query(" INSERT INTO `sort_votes` (ip,date_submit,dt_submit)
VALUES ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW())");
// If the user has not voted before today:
if(mysql_affected_rows($link)==1)
{
mysql_query(' INSERT INTO `sort_objects` (id,votes) '.$str.'
ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
}
}
why isnt the ajax post request filtering through to my php file?
thank you so much, any help is much appreciated.
You're not sending opinionIFC parameter, try:
request.send('opinionIFC=' + opinionIFC);
You also need to set Content-type
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

How to refresh the page's cache if scripts have been updated?

I searched online to find a solution for refreshing user cache if the website has been updated. Couldn't find anything apart from setting version control on url of the script files...
I'm answering my question below, and need to know if this is a perfect code and might not keep refreshing in a loop. Please could someone let me know if any modifications are required?
My answer involves
a php script that checks selected files on the server for modification date.
on the html page, javascript gets the data from php via jQuery getJSON.
Then it checks for localstorage data regarding the files, this data is first stored if none found via html5 localstorage.
Then it compares dates between localstorage and php jSON data.
If there are new files on the server, it stores the new dates instead of the old dates on the localstorage for future visits.
Refreshes only if newer versions of the scripts are found.
Below is the code, and here's the jsfiddle: [ ::: jsfiddle ::: ]
Snippet is not allowing localStorage, instead try js fiddle: '/xepjcwsf/'
//Script to check (via php & javascript), if the files loaded into client's cache are old and refreshes the page if newer files found on the server.
$(document).ready( function() {
var newFileCacheDate;
//uncomment: //$.getJSON('scripts/file_date.php', function(jsonData){
setTimeout(function(){
newFileCacheDate = {"css_1":"30-01-2015","css_2":"28-01-2015","css_3":"07-03-2015","js_1":"28-02-2015","js_2":"02-03-2015"}; //uncomment: //jsonData;
var StoredData = getStorage();
var isUpdated = check_filedate(newFileCacheDate, StoredData);
if(isUpdated) {
console.log('files have been updated, isUpdated = true');
addNewStorage_and_refresh(newFileCacheDate);
}
//uncomment: //}).fail(function() { console.log( "Couldn't get the json data." ); });
}, 1000);
function addNewStorage_and_refresh(newDates){
if(typeof(Storage) !== "undefined") {
localStorage.setItem('filecache_date', JSON.stringify(newDates));
alert('filedate storage updated, refreshing');
location.reload();
}
}
function getStorage(){
if(typeof(Storage) !== "undefined") {
var fileCacheDate, stored_FileDates;
var dataToStore = {
"css_1" : '30-01-2014',
"css_2" : '28-01-2015',
"css_3" : '07-03-2015',
"js_1" : '28-02-2015',
"js_2" : '02-03-2015'
};
if (localStorage.getItem("filecache_date") === null) {
localStorage.setItem('filecache_date', JSON.stringify(dataToStore));
console.log('filecache=null');
return dataToStore;
}
else if (localStorage.getItem("filecache_date") != null) {
fileCacheDate = localStorage.getItem('filecache_date'),
stored_FileDates = JSON.parse(fileCacheDate);
console.log('filechache=present');
return stored_FileDates;
}
}
}
function check_filedate(newfile, oldfile){
var isItUpdated = false;
$.each(oldfile, function (key, olddata) {
if(Date.parse(process(olddata)) < Date.parse(process(newfile[key]))){
console.log('files have been updated = true');
isItUpdated = true;
return false;
}
});
return isItUpdated;
function process(date){ var parts = date.split("-"); return new Date(parts[2], parts[1] - 1, parts[0]); } //to convert and return date in standard format
}
});
/* THE PHP CODE
** Paste this PHP code as a separate "file_data.php" file for retrieving json data from **
*******************************************************************************************
<?php
$filenames = array(
"css_1" => 'file1_css.css',
"css_2" => 'file2_css.css',
"js_1" => 'file3_jscript.js',
"js_2" => 'file4_jscript.js'
);
$previousDate = array(
"css_1" => '0',
"css_2" => '0',
"js_1" => '0',
"js_2" => '0',
);
foreach ($filenames as $jsonVar => $filename) {
if (file_exists($filename)) {
$mtime = filemtime($filename);
$previousDate[$jsonVar] = date ("d-m-Y", $mtime);
}
}
echo json_encode($previousDate);
?>
*******************************************************************************************
*/
//Below code for demo purpose only.
$(document).ready( function() {
$('button#reset').on('click', function(){
localStorage.removeItem('filecache_date');
location.reload();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Check Console for Logs -->
Check Console for Logs
<br><br>
If you were unable to see console log before page refresh, click on the reset button
<br>
(page will refresh after resetting localStorage data)
<br><br>
<button id="reset">Reset </button>
<br><br>
EDIT: Although jsfiddle allows localstorage, the stackoverflow snippet tool doesn't allow it, so this code might not function on stackoverflow.<br><br>
<b style="color:red;">Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.</b>

Manually refresh page from another page, on the same server

I'm trying to use a code to set a MySQL flag to true from a PHP file (Let's say A). I would like to read this MySQL flag from another PHP file (B), that will be already opened. The question is: Is there any way to manually refresh this (B) page after changing the flag value from the first page (A)?
May be using cron or something similar, I don't really want to refresh page B every X seconds until it reads new flag value.
Use AJAX.
Inside B page create a request function to check the status of MySQL flag. If the flag is set to true, refresh the page.
In HTML of B program insert:
<head>
...
<script>
function enableChecker() {
setInterval( checkFlag, 10000); // Check each ten seconds
}
function checkFlag() {
xmlhttp = GetXmlHttpObject();
if ( xmlhttp==null ) return;
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState == 4 ) {
if ( xmlhttp.responseText == "OK" ) {
location.reload(); // Refresh the page
}
}
}
xmlhttp.open( 'GET', 'myCheckProgram.php', true ); // Call php program to check the flag value
xmlhttp.send( null );
return false;
}
</script>
</head>
<body onload="enableChecker()" >
Create a program called myCheckProgram.php
<?php
/* Blah blah to connect with database and query for flag */
$flag = // Result of query
echo $flag ? 'OK' : 'NOK' // Return OK if flag is true
?>

Is it possible to ping a server from Javascript?

I'm making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 entries, it will scale linearly with more).
I decided to go the route of pinging on the user's end. This way, I can load the page and just have them wait for the "server is online" data while browsing my content.
If anyone has the answer to the above question, or if they know a solution to keep my page loads fast, I'd definitely appreciate it.
I have found someone that accomplishes this with a very clever usage of the native Image object.
From their source, this is the main function (it has dependences on other parts of the source but you get the idea).
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.
Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.
Update 2: #trante was nice enough to provide a jsFiddle.
http://jsfiddle.net/GSSCD/203/
Update 3: #Jonathon created a GitHub repo with the implementation.
https://github.com/jdfreder/pingjs
Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.
Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:
function ping(host, port, pong) {
var started = new Date().getTime();
var http = new XMLHttpRequest();
http.open("GET", "http://" + host + ":" + port, /*async*/true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();
var milliseconds = ended - started;
if (pong != null) {
pong(milliseconds);
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
}
}
you can try this:
put ping.html on the server with or without any content, on the javascript do same as below:
<script>
function ping(){
$.ajax({
url: 'ping.html',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
You can't directly "ping" in javascript.
There may be a few other ways:
Ajax
Using a java applet with isReachable
Writing a serverside script which pings and using AJAX to communicate to your serversidescript
You might also be able to ping in flash (actionscript)
You can't do regular ping in browser Javascript, but you can find out if remote server is alive by for example loading an image from the remote server. If loading fails -> server down.
You can even calculate the loading time by using onload-event. Here's an example how to use onload event.
Pitching in with a websocket solution...
function ping(ip, isUp, isDown) {
var ws = new WebSocket("ws://" + ip);
ws.onerror = function(e){
isUp();
ws = null;
};
setTimeout(function() {
if(ws != null) {
ws.close();
ws = null;
isDown();
}
},2000);
}
Update: this solution does not work anymore on major browsers, since the onerror callback is executed even if the host is a non-existent IP address.
To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.
The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.
Ruby prior to 1.9 had a TCP-based ping.rb, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.
There are many crazy answers here and especially about CORS -
You could do an http HEAD request (like GET but without payload).
See https://ochronus.com/http-head-request-good-uses/
It does NOT need a preflight check, the confusion is because of an old version of the specification, see
Why does a cross-origin HEAD request need a preflight check?
So you could use the answer above which is using the jQuery library (didn't say it) but with
type: 'HEAD'
--->
<script>
function ping(){
$.ajax({
url: 'ping.html',
type: 'HEAD',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
Off course you can also use vanilla js or dojo or whatever ...
If what you are trying to see is whether the server "exists", you can use the following:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
This will return a true/false indication whether the server exists.
If you want response time, a slight modification will do:
function ping(url) {
var encodedURL = encodeURIComponent(url);
var startDate = new Date();
var endDate = null;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
if (data.query.results != null) {
endDate = new Date();
} else {
endDate = null;
}
},
error: function(){
endDate = null;
}
});
if (endDate == null) {
throw "Not responsive...";
}
return endDate.getTime() - startDate.getTime();
}
The usage is then trivial:
var isValid = isValidURL("http://example.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Or:
var responseInMillis = ping("example.com");
alert(responseInMillis);
const ping = (url, timeout = 6000) => {
return new Promise((resolve, reject) => {
const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&##/%?=~_|!:,.;]+[-A-Za-z0-9+&##/%=~_|]');
if (!urlRule.test(url)) reject('invalid url');
try {
fetch(url)
.then(() => resolve(true))
.catch(() => resolve(false));
setTimeout(() => {
resolve(false);
}, timeout);
} catch (e) {
reject(e);
}
});
};
use like this:
ping('https://stackoverflow.com/')
.then(res=>console.log(res))
.catch(e=>console.log(e))
I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/
let webSite = 'https://google.com/'
https.get(webSite, function (res) {
// If you get here, you have a response.
// If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
// Here, an error occurred. Check `e` for the error.
console.log(e.code)
});;
if you run this with node it would console log 200 as long as google is not down.
You can run the DOS ping.exe command from javaScript using the folowing:
function ping(ip)
{
var input = "";
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);
while (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.ReadLine() + "<br />";
}
return input;
}
Is this what was asked for, or am i missing something?
just replace
file_get_contents
with
$ip = $_SERVER['xxx.xxx.xxx.xxx'];
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) {
echo "no!";
}
else{
echo "yes!";
}
It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.
yourpage.php
<?php
if (isset($_GET['urlget'])){
if ($_GET['urlget']!=''){
$foreignpage= file_get_contents('http://www.foreignpage.html');
// you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
// parse $foreignpage for data that indicates your page should proceed
echo $foreignpage; // or a portion of it as you parsed
exit(); // this is very important otherwise you'll get the contents of your own page returned back to you on each call
}
}
?>
<html>
mypage html content
...
<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);
function getforeignurl(url){
var handle= browserspec();
handle.open('GET', url, false);
handle.send();
var returnedPageContents= handle.responseText;
// parse page contents for what your looking and trigger javascript events accordingly.
// use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
</script>
That should do it.
The triggered javascript should include clearInterval(stopmelater)
Let me know if that works for you
Jerry
You could try using PHP in your web page...something like this:
<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php
$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');
echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";
?>
This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...

Categories

Resources