reading a text file line by line only with javascript - javascript

I don't want solution using Node.js, FileReader, or whatever else exept javascript!
Developing the html page, I encountered a problem as follows:
I get accurate results with this procedure, unfortunately the procedure remembers result of the first login page. Whatever text file in the meantime change the content, the procedure returns the first result.
Can someone give advice!
var filePath = "../../dir/sub dir/text_file.txt";
function getBackData(filePath){
var axd, i, artx, txli, tdr;
if(window.XMLHttpRequest){
axd = new XMLHttpRequest();
}else{
axd = new ActiveXObject("Microsoft.XMLHTTP");
}
axd.open('GET', filePath, true);
axd.onreadystatechange = function(){
if(axd.readyState == 4 && axd.status == 200){
artx = axd.responseText;
txli = artx.split("\n");
for(i = 0; i < txli.length; i++){
alert(txli[i]);
}
}
}
axd.send(null);
}

You could try :axd setRequestHeader('Cache-Control', 'no-cache');
Or try: axd.open('GET', filePath+'?_=' + new Date().getTime()), true); This will prevent your server from using the cash, because each request is different.

This is probably because the browser cache it. If you send a parameter which is almost always different like timestamp, you can disable the cache. Or you can try to use POST, since post request are never cached.

You are not allowed to request local files directly with ajax - you need a server to serve them. The browser is sandboxed and cannot generally open local files. This is a security measure - imagine what would happen if any website was allowed to open your files!
There are ways to set up a simple server for your images, like http-server. This allows you to serve files directly off a chosen directory, like so:
npm install -g http-server
http-server path-to-text-files/
Then you can request the files normally with ajax, at a path relative to the one your server is serving, like so:
url = "/dir/subdir/text-file.txt";
...
ajax.open('GET', url, true);
...
ajax.send(null);

Related

JavaScript / Python interaction in Linux without a REST framework?

I'm working on some changes to a page that needs to retrieve information from some files under /proc so the page can display version information to the user. Currently, the page is generated entirely by the Python script, which allows me to just read the file and put everything in the page at creation time.
However, this led to the issue that the version numbers wouldn't update when a new version of the software was uploaded. I don't want to regenerate the page every time a new package is installed, so I made the main page static and want to instead just query the information from a Python script and return it to the page to populate the page when loaded.
The Python scripts are set up as CGI and have sudo access, so there's no issue with them retrieving those files. However, if I wanted to use something like AJAX to call the Python script, is there any way I could return the data without using a REST framework such as Flask or Django? The application needs to be lightweight and preferably not rely on a new framework.
Is there a way I can do this with vanilla JavaScript and Python?
Ok, so the solution was fairly simple, I just made a few syntactical errors that led to it not working the first few times I tried it.
So the request looked like this:
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if((this.readyState == 4) && (this.status == 200)) {
var response = JSON.parse(this.responseText);
// Do stuff with the JSON here...
}
};
xhr.open("GET", scriptURL, true);
xhr.send();
}
From there, the Python script simply needed to do something like this to return JSON data containing my version numbers:
import sys, cgi, json
result = {}
result['success'] = True
result['message'] = "The command completed successfully"
d = {}
... write version information to the 'd' map ...
result['data'] = d
sys.stdout.write("Content-Type: text/plain\n\n")
sys.stdout.write(json.dumps(result))
sys.stdout.write("\n")
sys.stdout.close()
The most persistent problem that took me forever to find was I forgot a closing quotation in my script tag, which caused the whole page to not load.

In a node.js API how do I perform tasks that must be synchronous without freezing the browser?

To start off this is what I am trying to accomplish:
I am trying to do file copies to an array of servers. There are several steps that must be completed in a specific order before and after these copies (for example, stopping IIS, backing up and clearing folders, running a bat file, etc) so they are not single operations.
To make this super easy I wrote an API in node.js that does simple tasks like copy files and folders, delete folders, etc. I then wrote a frontend in node.js using an express generator and Pug that uses javascript XMLHhttpRequests to send commands to the API depending on what I needed to do. I have the API written and running as well as the frontend. Now on to the problems:
If I have my XMLHttpRequest run in synchronous mode (example: xhttp.open("POST", url , false);) when the command is sent to the API to copy a folder if the folder takes several minutes to copy the browser freezes. Chrome displays a "Page Frozen" error. However, the job gets done correctly.
If I have my XMLHttpRequest run in asynchronous mode (example: xhttp.open("POST", url , true);) then every command gets sent to the API at once so that the fastest operation completes first and the commands are out of order. The copy will fail.
I've tried searching for a way to make it so that each operation sent from the frontend javascript has to return a SUCCESS (or 200 response) from the API before moving on to the next command but so far all I've seen is "just use synchronous". Right now that's what I'm doing. That doesn't seem like the best solution even though it works. Is there a better way to do this in a way that won't freeze the browser?
I figured this out by writing a function to handle the requests, setting a counter (for the steps of the process), and putting a switch statement in the if statement for the result. It wasn't exactly what I needed but the basics of my solution is in the answers to this question: How can I call ajax synchronously without my web page freezing
Here's what I did in case it helps anyone else who finds this question:
function myFunction (step, params, url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
switch(step) {
case 2:
//url and params are set here, and step 2 is done here
myFunction(step, params, url);
break;
case 3:
// and so on and so forth
}
}
xhttp.open("POST", url , true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
step++;
}
//kick off the function
var step = 1;
var url = "my URL to the API with call";
var parameters = "my parameters";
myFunction(step, parameters, url);

Why is this a Cross Domain Request and how to solve it? [duplicate]

I'm currently working through the book "Head first HTML5 programming". I want to load the content of a file named sales.json from a web server on my own machine. I used wampserver for this.
In the folder wamp/www/gumball/ I put all relevant .html, .js and .css files, and also the sales.json file.
My JavaScript code is very simple:
window.onload = function() {
var url = "http://localhost/gumball/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
This doesn't do anything! Typing the link: http://localhost/gumball/sales.json in my browser opens the right file, so the link should be correct. Even when using the .js files that come with the book (with a finished version of the application I'm trying to make), nothing loads.
Testing with alert statements tells me the request.onload event never happens. I'm clueless as to why this is the case.
A fact I don't quite understand yet: when I type: http://localhost/gumball/sales.json: in my browser (I added a colon at the end of the link), I get a 403 Forbidden error! Why does this happen? Does this have something to do with my problem?
I open html document with firefox
Your HTML document must be open with a URL in http://, not file://, if you want it to be able to open in javascript another document, unless the second document is served with relevant CORS headers.
This is due to same origin policy.
As you have a local WAMP server, there is no problem : simply open your file using a http:// URL like you do for your JSON file.

Get text from a link in javascript

I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.

Javascript : Different behavior when run on machine and local server

Because my title is too short, I will explain more clearer. I have create a code in JavaScript . And I have two options to run :
1) Run on machine : simple click into html file.
2) Run on local server : mean I start Apache, and start this html file in localhost.
( http://localhost:85/Javascript/index.html for example)
When I choose solution 1, no thing happen. And when I choose solution 2, happen as I wish. But I don't know why.
Here is my code. Purpose : take a json file and process it.
<script>
window.onload = function(){
var url = "http://localhost:85/javascript/json1.json"; // problem here
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function(){
if (request.status == 200){
update(request.responseText);
}
}
request.send(null);
};
function update(responseText){ // some code here }
</script>
You cannot use AJAX to read content from a different domain.
Javascript running from file://whatever cannot read localhost:85.
Did you replace this line with the server's original path?
var url = "http://localhost:85/javascript/json1.json";
With
var url = "http://10.0.0.X:85/javascript/json1.json"; // Did you change the right path?
And make sure, the page is not called with the file:// protocol!

Categories