JavaScript Basic Solution for Retrieving Files - javascript

I'm very new to JavaScript, so please be patient with me. I've got a CSV file published to the web via Google, which is updated periodically. I have the URL of the file, and I want to write JS code which will retrieve that file when an HTML page is loaded, then convert it into a string so I can manipulate it and scoop out the values I want to place in different elements. The problem is, I have no idea how to request items from different URLs. I'm guessing there's some built-in functionality in JS to do what I want, but I'm completely in the dark on how to find it. Care to help me out?

What you're looking for is the XMLHttpRequest, but I'd recommend using jQuery's $.ajax() function as it decreases the complexity of sending asynchronous requests.

You can use jquery $.ajax or better Fetch API or axios to get the file contents.
Then you need to process it by using something like Papa Parse.
PS. Papa Parse actually supports remote files directly so you can try that.

Sounds like what you're looking for is AJAX.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
doSomethingWith(this.responseText);
}
};
xhttp.open("GET", "http://url/file.csv", true);
xhttp.send();
You could also use jQuery's ajax function :
$.ajax({url: "http://url/file.csv", success: function(result){
doSomethingWith(result);
}});
This way, you get the result as a string which you can then use to retrieve the CSV values - look into the split function for instance.
Be aware that you will not be able to try this locally without a webserver, since your browser will not allow your Javascript to fetch files from your computer. Indeed, your browser implements a mechanism called CORS which restricts HTTP requests heading to a different domain.

Did you publish that .csv to google ? If so , can you program the file to be dumped to your web-content file?
I found I couldn't get files out of google drive with js, a lot of people had problems with this, then I tried to find a solution for it. So instead you can use platforms like github, or host on your server. Then the problem becomes way more straight forward.
I used python to grab the content I wanted , turn into .js file, or json file. Then use javascript to retrieve it.
var data = http://mywebsite.com/my_file.json
or script src = http://my_website/data.js /script
Sorry about the above. Stackoverflow messing with my js. The above is just an example of the script tag 'my_website' needs to be programmes in.
Great place to start with json , and other resource here
https://www.w3schools.com/js/js_json_intro.asp

Related

Again: how can I read a file using javascript

I could not find out why this part of my code doesn't work:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
var FilePath = dir + "/" + FileName;
var file = new File("FilePath");
var reader = new FileReader();
reader.onload = function(e) {FileText = reader.result;}
reader.readAsText(file);
alert (FileText);
The intention is, I think, clear: FilePath contains the filename of a file (passed via parameter FileName) containing logging data (a plain ASCII text file, with one line per log entry), the file is located in the same directory as the web page is (loc), and I want to embed the text into my html document somewhere further down the code.
Since the logged lines are of different kinds (e.g. errors, warning, other blabla ...) each line needs to be parsed and processed.
I intended to split FileText into an array, and loop through it. I cannot, however, get readastext to work. Though, according to FireFox debugger, FilePath does contain the correct string, I get the NS_ERROR_FAILURE, which I, according to the sparse documentation I found about it, must consider to be the 'zillionst stupid way to say "File not found".
I found tons of other posts from people messing with the file API, and tons of snippets taken from the mozilla docs which don't help me out. I read that there are maybe other ways to read a file, e.g. through Ajax, JQuery ... but before I go that way ... is it really, really absolutely impossible to accomplish what I want using just plain JavaScript, and if it is possible, who can provide a code snippet?
Thanks very much,
Armin.
You have quotes around "FilePath":
var file = new File("FilePath");
This means it's going to try to load a file with the path "FilePath".
Pretty sure this is what you want:
var file = new File(FilePath);
On the other hand, Quentin is absolutely right. You're not going to be able to access local files if this code is running in a web page.
Since you are using window.location.pathname i assume that you are in a browser and want to use that code to "navigate" to files on the server based on the URL path.
I think your whole approach is wrong, and it would be a security issue to have something like that possible.
The File API can be used strictly on files selected by the user, and not on any file. The MDN description is self-explanatory:
Using the File API, which was added to the DOM in HTML5, it's now possible for web content to ask the user to select local files, then read the contents of those files. This selection can be done by either using an HTML element, or by drag and drop.
Yes, you can specify a path to any file in the File constructor method, but that doesn't mean you can access any file. Another excerpt from MDN:
This only works from privileged code, so web content can't do it. This protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. If you pass a path to the File constructor from unprivileged code (such as web content), an exception will be thrown.
This code did the trick:
var objXMLhttp = new XMLHttpRequest()
objXMLhttp.open("GET",strFileName,true);
objXMLhttp.send();
and, in addition, an objXMLhttp.onreadystatechange=function() ... event handler must be implemented, which is the code acutally receiving the data, like so:
objXMLhttp.onreadystatechange=function()
{
if (objXMLhttp.readyState==4 && objXMLhttp.status==200)
{
var arrContents = objXMLhttp.responseText.split("\n"); // gotcha!
....
}
}
Easy win is to do an ajax request for the path...you should have your page that contains the js and files served by a web server. Any other way needs other priveleges and if you were to get files from a users computer without an uploader or anything like that would be a security breach

Write to file in JS using XMLHttpRequest?

I figured out how to read a local .TXT file on the server into JS using the XMLHttpRequest API but for the life of me I cant get it to write to the file. Is it possible or is this only for reading the files in?
My code to read in works fine:
var fReader = new XMLHttpRequest();
fReader.onreadystatechange=function() {
if(fReader.readyState==4 && fReader.status==200) {
parseText(fReader.responseText);//Processes the file.
}}
fReader.open("GET",fFileLoc,true);
fReader.send();
I'm currently using PHP to write to the file, but it's far from ideal. I'd really like to us JS to do it. Any thoughts? Is there another approach to doing this? Is PHP the only way?
Thanks in advance,
-Dave
EDIT: #rjmunro +others: I found that using PHP was the better way to go about this... My revised code is as follows. (C&C welcome).
JS:
var fReader = XMLHttpRequest();
//var params = "MODE=GET&File=Data.txt";//To read
//var params = "MODE=POST&File=Data.txt&Message=" + myMessage;//To write
fReader.onreadystatechange=function() {
if(fReader.readyState==4 && fReader.status==200) {
//Not really any response text if writing...
parseText(JSON.parse(fReader.responseText).GET);
}
}
fReader.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
fReader.setRequestHeader("Content-length", params.length);
fReader.setRequestHeader("Connection", "close");
fReader.send(params);
PHP
$MODE = $_POST['MODE'];
switch($MODE) {
case('GET'):
#Read in file and process, then return output.
$return['GET'] = file($_POST['File']);
break;
case('POST'):
if(file_exists($_POST['File'])){
$file = fopen($_POST['File'],"a");
$data = $_POST["Message"];
fwrite($file,$data);
fclose($file);
}
#$return['POST'] = "some message?";
break;
}
echo json_encode($return);
The only thing i'm not 100% on with this solution is why i have to setRequestHeader?
Chrome actually doesnt seem to like this... I pulled the code from another post.
XMLHttpRequest allows you to make HTTP requests.
If you want to use it to write to a file, then the HTTP server must respond to the request by writing a file.
You could use the PUT verb to do this (note that you will have to configure the HTTP server to allow this, no HTTP server will allow arbitrary users to write files to the server's disk by default).
You could also pass the data using POST or another request type.
Is PHP the only way?
You can use any programming language you like on the server (subject to what the server supports, e.g. if you want to use C# then you almost certainly want a Windows server with IIS and ASP.NET). If you want to use JavaScript then there are many options, of which Node.js is significantly more popular then the others at present.
You can probably configure apache to accept PUT requests, then send one using XMLHttpRequest (I'd use jQuery.ajax() to abstract this).
It's probably better to have PHP (or another server side language) handle it for you, though, as it will be difficult to control the authentication using only Apache.

Javascript Read Text File Offline

Currently I use this code to read a txt file with words and perform some operations. However, this particular code requires the html to be deployed on a server. Is there any workaround where I can replace this code with something else to read the file without the need of a server?
var xhr = new XMLHttpRequest();
xhr.open( "GET", "dictionary.txt", false );
xhr.send( null );
var words= xhr.responseText.split(",");
It is NOT possible to call Ajax outside your server domain (except you use scriptagproxy, that too requires you to have some server side configuration). So, in short, you CANNOT read files on your local computer using Ajax calls.
You might like this article.
The file selection can be made either by input or drag-and-drop (not otherwise). Please see: this
You cannot read files from the clients' computer, so the text file you are reading must be on the same server as your javascript.
However, if you are loading the HTML file from your computer (e.g. file://c:/../test.html), you might be able to read files located on ONLY your computer by using relative paths.
You can hide an iframe on the page, with its src='dictionary.txt',
and read or manipulate the iframe's local content when it's onload event fires.

Reading local XML file with javascript

I am new to HTML/Javascript, as well as coding in general so bear with me :). I am trying to create a "Spot the Difference" game in html5 using javascript. Everything is local (on my machine). I have two pictures, of the same size, one with differences. To generate data about the clickable fields, I have a java program that reads both of the images and outputs all of the positions in which pixels are different into a XML file. My plan was to then use this XML file with my javascript to define where the user could click. However, it appears (correct me if I'm wrong) that javascript cannot read local XML files for security reasons. I do not want to use an ActiveXObject because I plan on putting this onto mobile devices via phone gap or a webkit object. Does anyone have a better approach to this problem, or perhaps a way to read local XML files via javascript? Any help would be greatly appreciated, thanks.
If you are planning to put this into a smart phones (iOS and Android) and read local files, I have done similar things with JSON (yes, please don't use XML).
Convert your output to JSON
Put this as part of your application package. For example, in Android, I put it as part of the .apk in /appFiles/json
Create a custom content provider that would read the local file. I create mine as content:// but you create whatever scheme you want. You could leverage android.content.ContentProvider in order to achieve custom URL Scheme. iOS has its own way to create custom scheme as well. The implementation simply read your local storage and give the content
To read it from Javascript, I simply call ajax with the custom scheme to get the json file. For example content://myfile/theFile.json simply redirect me to particular directory in local storage with /myfile/theFile.json appended to it
Below is the sample to override openFile() in the ContentProvider
public ParcelFileDescriptor openFile (Uri uri, String mode) {
try {
Context c = getContext();
File cacheDir = c.getCacheDir();
String uriString = uri.toString();
String htmlFile = uriString.replaceAll(CUSTOM_CONTENT_URI, "");
// Translate the uri into pointer in the cache
File htmlResource = new File(cacheDir.toString() + File.separator + htmlFile);
File parentDir = htmlResource.getParentFile();
if(!parentDir.exists()) {
parentDir.mkdirs();
}
// get the file from one of the resources within the local storage
InputStream in = WebViewContentProvider.class.getResourceAsStream(htmlFile);
// copy the local storage to a cache file
copy(in, new FileOutputStream(htmlResource));
return ParcelFileDescriptor.open(htmlResource, ParcelFileDescriptor.MODE_READ_WRITE);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
I hope it helps
I would suggest modifying your java program to output a JSON formatted file instead of XML. JSON is native to JavaScript and will be much simpler for you to load.
As for actually loading the data, i'm not sure what the best option is as you say you want to evenutally run this on a mobile device. If you were just making a normal website you could setup a web server using either Apache or IIS depending on your OS and put the files in the document root. Once you've done that you can load the JSON file via Ajax, which can easily be googled for.
Not sure if this helps any.
Since this is a local file, you can do this with jQuery
$.ajax({
type: "GET",
url: "your.xml",
dataType: "xml",
success: function(xml){
///do your thing
}
});
http://api.jquery.com/jQuery.ajax/

how to load xml data from server in client side using javascript or vbscript?

It's been almost three weeks and I'm Googling around. my eyes got tired and headaches was included too.
I couldn't do it what even 8-10 hours daily computing :(
I have some data that saved in a valid XML file on the server(domain or sub-domain)
I've choosed XML because I'm may or probably need it for other future application use.
What I want to do is:
1- including the XML file and load it on a client side HTML page.(does sub-domain or normal domain make a difference while including?)
2- I do prefer using JavaScript (or Vb Script) or any other client side script(if available) for parsing or manipulating thing.
And If you do prefer me a better way to include a server side XML file including....I'm listening
EDIT:
I'm working on AJAX now but why I can't get data from a URL?
something like:
xmlhttp.open("GET","https://www.mywebsite.com/xmlfile.xml",true);
buy it's not working :(
Because you haven't given the actual code that you're using, I am guessing here and have put together an HTA that you can try. This only works on Windows (as I believe that is the platform you're targeting). Copy this code into a text file and save it with a .hta file extension:
<html>
<head>
<title>HTA Ajax Example</title>
<script type="text/javascript">
var ajaxRequest = function() {
var http = new ActiveXObject('MSXML2.XMLHTTP');
http.onreadystatechange = function() {
if(http.readyState === 4 && http.status === 200) {
var div = document.getElementById('target-div');
div.innerHTML = http.responseText;
}
}
http.open('GET', 'http://www.w3schools.com/ajax/ajax_info.txt', true);
http.send();
return true;
}
</script>
</head>
<body>
<div id="target-div"></div>
<input type="button" value="load" onclick="ajaxRequest();"></input>
</body>
</html>
On clicking the Load button, the text from your w3schools example will be loaded into the page. This should get you started. Should you want to provide a cross-platform solution, a library like jQuery will handle all the differences for you.
As mentioned before, the url used in the request is a full url to a resource on a different server. This won't work if you put this code on a server because of the cross-domain security issue.
If you want to pick up information from an XML file, you might want to use http.responseXML rather than http.responseText. The former property makes the response available as an XML document object rather than a text string.
including the xml file and load it on a client side html page.
Use Ajax, and use a library to access it.
does sub-domain or normal domain make a difference while including?
If it is different to the page: yes
Can you use AJAX? http://www.w3schools.com/ajax/default.asp

Categories

Resources