Best way to get file last modified attribute - javascript

What would be the best way to get the "last modified" attribute from a file NOT on the web server. My purpose is to display the time stamps of specific network files in a web page. All the JavaScript references I have found are for the current file, or from the web server. I have found references for browsing to, drag-and-drop, etc. But I would like to read the file attribute from the original location. Is this even possible??
EDIT:
So now that I have a batch file to create the text file on the web server, how do I get that data into an array so I can display it properly? The data is correct, but it is one long string.
This is my code:
<html>
<head>
<script type="text/javascript">
function getStatus() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("backupStatus").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "file.txt", true);
xhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="getStatus()">Get QNAP Backup Status</button>
<ul id="backupStatus">
</ul>
</body>
</html>
This is my output:
#ECHO 4/13/2016 #FREEMAN1 4/13/2016 #FREEMAN02 4/13/2016 #FREEMAN03 4/7/2016 #FREEMAN4 4/7/2016 #FREEMAN5 4/7/2016 #HR10 4/13/2016 #ACCOUNTING20 4/12/2016 #IT01 4/13/2016 #PROD20 4/12/2016 #UPS10 4/13/2016

javascript can't go out and read files on a user's computer. You'd need to read this information on a server and load it in to the page, or via an ajax call.

Related

dynamically loading JSON file from javascript

On my RPi I have an application (developed in C++) running in the background that does some complex mathematics based on some sensor input and produces some result every second. I want to display this data on a website. So I had the idea to have the application produce a JSON formatted file and read that interactively from a javascript script.
The app now produces a file ModelState.json in my html directory that looks like
{ "x" : -0.886289 , "y" : -0.434931 }
Based on this answer, I wrote the following html/js
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p id="ModelState"></p>
</body>
<script type="text/javascript">
window.onload = function () {
setInterval(showModelState, 1000);
function showModelState() {
readJsonFile("ModelState.json", function(ModelStateJson){
var ModelStateObj = JSON.parse(ModelStateJson);
if (ModelStateObj.x && ModelStateObj.y) {
document.getElementById("ModelState").innerHTML =
"x: " + ModelStateObj.x + ", " +
"y: " + ModelStateObj.y;
}
});
}
function readJsonFile(file, callback) {
let rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status === 200) {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
}
</script>
</html>
However, what I observe is that the file seems to be loaded once. The data on the webpage doesn't change, while the data in the file does change.
I don't know why. Is it that the XMLHttpRequest keeps the file open, such that onreadystatechange is not triggered and the callback function is not called again? I would expect the send response to finish the request, thus close the file.
As cristobal states in the comments, the problem is caused by the browser caching the read file.
One solution is to confuse the browser with a dynamic url, e.g. by changing
readJsonFile("ModelState.json", function(...
to
readJsonFile("ModelState.json?time=${Date.now()}", function(...
An alternative solution (based on this) is that the browser doesn't cache POST http request methods. Thus you can change
rawFile.open("GET", file, true);
to
rawFile.open("POST", file, true);
A third solution (found here) is to add a pragma after the line rawFile.open("GET"...
rawFile.setRequestHeader("Pragma", "no-cache");
More elaborate request headers for cache control can be found here

ajax simple code not working

I know I might just be missing a simple thing that's right under my nose, or may not understand ajax at all... but I have a problem - this simple peace of code isn't working, but it's from w3schools and it's the simplest example of ajax working.
Can someone help me, please?
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
Here's the "ajax_info.txt" file:
text changed.
If you're opening the file in the browser with file:// or C:/ protocol you'll get a cross origin request error when trying to load 'ajax_info.txt', the reason for this is to protect your machines private files from being read by browser scripts. To fix this you'll need to use the protocol http:// which you can do if you install a webserver onto your local machine such as WAMP or MAMP.
Additionally a file called ajax_info.txt needs to exist in the same directory as this html file. Otherwise this javascript AJAX call will return an error: /ajax_info.txt 404 (Not Found)

How is url parameter in open method of XMLHttpRequest used?

MDN tells me that the specification of the XMLHttpRequest open method includes the bstrUrl parameter and that this parameter represents "The requested URL." Vague to say the least.
www.help.dottoro.com tells me that the parameter contains the "String that specifies the URL where the request needs to be sent."
W3Schools has this example:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
This example triggers the text to be displayed when the button is clicked.
My book tells me it is "The path to the page that will handle the request." Then I see an example in my book of where a .json file is specified in that parameter which contains data that is then displayed in html.
I'm confused. How does js know what the specified file is for?
How is url parameter in open method of XMLHttpRequest used?
It's the URL that the XMLHttpRequest object will ask the browser to send the GET or POST to.
How does js know what the specified file is for?
The person writing the JavaScript writes code that knows what to do with the specified resource.
In your w3schools example, the code knows that it's requesting something that will return HTML it wants to display in the demo element.
If the request were for JSON, the code would handle a successful request by parsing the JSON and doing something with the data.

Trying to use XML returned by merriam webster dictionary API but request getting failed. Status returned is zero. What to do?

I saw this great API (http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm) by merriam webster that returns an XML file with all the details in it including definitions and pronunciations.
This API requires a key so i registered and got a key for my account.
I am making the request using Javascript(XHR) but the status returned is zero.
Then i googled the error it said that it may be because my request is going from a "file:///" protocol instead of "http://", so i installed LAMP stack on my PC then hosted the file on my localhost server and even then no luck.
Another thread said that i cant make cross domain requests.
Please can you help me. Below is my HTML code from which i call function in my javascript file.
<html>
<head>
<script type="text/javascript" src="context-script.js">
</script>
</head>
<body>
<h1>Merriam Webster</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span><br/>
<b>Sound:</b><span id="sound"></span><br />
</div>
<script>
callOtherDomain();
</script>
</body>
</html>
Below is my JAvascript file context-script.js code:
function callOtherDomain()
{
invocation = new XMLHttpRequest();
var url = 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/happy?key=8f394b2c-77e8-433d-b599-f3ca87660067';
//url="note.xml";
if(invocation)
{
invocation.open('GET', url, true);
invocation.withCredentials = "true";
invocation.onreadystatechange = handler;
invocation.send();
alert("ref");
}
}
function handler(evtXHR)
{
if (invocation.readyState == 4)
{
alert("erg");
if (invocation.status == 200)
{
var response = invocation.responseXML;
document.getElementById("to").innerHTML=
response.getElementsByTagName("dt")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
response.getElementsByTagName("dt")[1].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
response.getElementsByTagName("dt")[2].childNodes[0].nodeValue;
}
else
alert(invocation.status);
}
else
dump("currently the application is at" + invocation.readyState);
}
But when i change the URL to "note.xml" which is locally stored on the localhost code works absolutely fine.
Thanks in advance.
While this question is several years old, I worked with dictionaryapi.com previously and the solution is two-fold:
Your first step to host on a local server was right on (localhost:8000 or http://127.0.0.1:8000). I prefer using the Python SimpleHTTPServer, started in the root directory of the page you're trying to host with whichever CLI tool you're most familiar/comfortable with, py -m http.server.
After that, just complete a jQuery call using ajax, get, or XMLHttpRequest—whichever you prefer. For example:
$.ajax({
url: 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/[YourWord]?key=[YourKeyHere],
method: "GET"
}).done(function(response){
console.log(response);
});

How to read Live streaming data using AJAX

I want to read live streaming data from my URL(ie.http://..)
My URL(ie.http://..) contain numeric data and it's continuously growing.
i want to read that data in to my file(HTML5 & javascript).
I have done with static numeric data using AJAX.
But while duing it with dynamic data(live streaming data). i am not able to get responseText().
Is it possible to take responseText() of that URL(ie.http://..) which contain live streaming data?
how i can do this?
My code for reading static data is
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function accessWebservice()
{
var xmlhttp;
xmlhttp = new XMLHttpRequest();
//xmlhttp.open("get","http://192.168.15.174/Streamer/StartStream.aspx?IsTestData=true",true);
//above URL contains live streaming numberic data that i want to read
//But when i am using above URL i am not getting responseText (**How to get it?**)
xmlhttp.open("get","http://localhost/StaticDemoData.txt",true); //This contains static data
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4)
{
if (xmlhttp.status == 200 )
{
var responseData=xmlhttp.responseText;
alert(responseData);
}
else
{
alert("Server returned: " + xmlhttp.status);
}
}
}
xmlhttp.send(null);
}
</script>
</head>
How to get 'xmlhttp.responseText' for live streaming numeric data?
If you check for xmlhttp.readyState == 3 (XMLHttpRequest.LOADING), then accessing xmlhttp.responseText will give you the data that has been received from your server so far. You can then use a setInterval to constantly check xmlhttp.responseText for new data.
Try this script to get stream your data... but you need jquery.js file in your directory and StaticDemoData.txt you can change with other file in .php extension and get your query on the file
<html>
<head>
<script type="text/javascript" src="jquery-1.5.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
userdetails();
});
function userdetails(){
$.post('StaticDemoData.txt',function(data){
$('.result').html(data);
});
setTimeout("userdetails()",1000);
}
</script>
</head>
<body>
<div class="result"></div>
</body>
</html>

Categories