Loading a JSON file into JavaScript (possibly without JQuery) - javascript

I was used to handle data using PHP + PostGreSQL and, after a SQL query, print data in table using
while($var= pg_fetch_assoc($result)){
echo <<<PRINT
<tr>
<td>{$var['id']}</td>
<td>{$var['name']}</td>
<td>{$var['surname']}</td>
<td>{$var['placement']}</td>
</tr>
PRINT;
Now I have a similar problem but I have to handle JSon files only using JavaScript and no JQueries/AJAX syntax. I made some reasearch and found out that seems not possible to load data using JavaScript for security reasons, but it feels kinda odd since you can manipulate all kind of media-type files.. and you cannot get JSon text files from your disk.
So, is it really possible to load JSon files using JavaScript and then being able to manipulate it ciclicaly?

Well, depends, if you mean a local .JSON file you could simply use require to get the object, to manipulate it you could either use fs or klaw

Deal with files on the PC, form the browser
Maybe you should test something from the File Web API.
Search for "File" here.
Deal with files on a server, form the browser
You publish your JSON at some URL and then GET the JSON with AJAX.
See: https://www.w3schools.com/xml/ajax_intro.asp

You can modify files with http protocols.
I paste this link, to make a mini web server https://sourceforge.net/projects/miniweb/

First of all you can't access a local file directly from the browser. File should be served over a local server, specially if you are using Chrome. Since Chromes security is much tighter than Firefox or others, loading anything using xhr, Josn, Xml etc is pretty much all locked down.
you can use simply use apache, python or node to set up a simple local server.
Then use Fetch API. All modern browsers support Fetch API except Internet NOBODY USING Explorer.
fetch('/path/to/test.json')
.then(response => response.json())
.then(json => console.log(json));
done..! hope it helps.

Related

Read local text file using js/html file on on local machine

I've built a simple html page with javascript in a separate file, called on a button press.
I've opened the html file in chrome, and the path resembles: file:///home/tom/projects/index.html
The javascript needs to read a JSON file (file:///home/tom/projects/mydata.json) which is in the same directory, using a hardcoded path.
I'm really struggling to do this. As I understand, this is because I'm using client side js (meaning I can't use the fs library for example), which is limiting my options.
According to the question here, I can't load the file if I use the URL in the format: file:///home/to.... as it gives me the error:
Cross origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https.
If I start an HTTP-server, as the answer suggests, I can use server-side modules, but if possible I would like to avoid this.
I've noticed many answers that suggest using a dialog box like this:
var selectedFile = document.getElementById('input').files[0];
function readFile (file_path) {
var reader = new FileReader();
reader.readAsText(file_path);
console.log(reader.substring(0, 100));
};
but I can't make this work with a path in the form: file:///home/tom/projects/mydata.json
Is there a way to load a .json file from a file:///home/to.... format URL using client-side javascript, with a hardcoded path (ie not asking the user to select the file from a selection box)?
This is a deliberate security restriction, to stop a user from being given, and then opening, a HTML page which then tries to read their disk.
Run your page in a webserver (as that question suggested) then you can either load the JSON from a URL (e.g. something like http://localhost/projects/mydata.json) using JavaScript, or use a server-side language to fetch it and display it inside the rendered HTML. Either way will work, the first way is probably simpler and closest to what you've got now.
It's always far better to serve HTML pages from a HTTP server, the way it's intended to be.

D3 visualization on local machine without HTML server?

I'm a total novice in web development. I'm interested in using D3 to create interactive visualizations for my (insurance) work, not for sharing on web. The visualization would need to be pretty self-contained so non-tech-savvy business users can view it without special software setup--just the usual browser, internet access, and access to the same LAN locations I have. Below is my initial investigation into viability.
1) I can save this HTML example to my local machine and view the chart in a browser, no probs: https://bl.ocks.org/mbostock/b5935342c6d21928111928401e2c8608
2) Then I tried a visualization that uses a data file.
https://bl.ocks.org/mbostock/2838bf53e0e65f369f476afd653663a2
I went to the data source website and downloaded the .csv. Simply changing the file address in the d3.csv() command to my local drive didn't work (as I mentioned I'm a novice)
Can anyone show me how to make (2) work locally? I found some related answers
Loading local data for visualization using D3.js
Reading in a local csv file in javascript?
but still over my head--if someone can work the example (2) above I can probably understand better...
There are two techniques you can use to load d3 data without a server:
load the data yourself without using d3.csv() helpers.
use data-urls with d3.csv() to avoid server loading.
Loading the data yourself without d3.csv()
Your first example: Stacked Negative Values works because data is defined at the top of the page without using d3.csv():
var data = [...];
...
// d3 operates on the data
Your second example: Nested TreeMap doesn't work because the data is loaded by d3.csv() which takes a path, which ordinarily takes assumes a server:
d3.csv("Home_Office_Air_Travel_Data_2011.csv", type, function(error, data) {
...
// work on data within the anon function passed to d3.csv.
Using data-urls with d3.csv()
However, if you use a data-url as the path, you can get this to work without a server:
var data = [...];
var dataUri = "data:text/plain;base64," + btoa(JSON.stringify(data));
d3.csv(dataUri, function(data){
// d3 code here
});
Adapted from: Create data uri's on the fly?
As an aside, you may be interested in a Middleman plugin I wrote that creates self-contained d3 HTML pages that can be run from the file system without a server using these approaches:
https://github.com/coldnebo/middleman-static-d3
Most modern browsers (chrome, mozilla) have full built in html5, css3, and javascript support without need of a webserver (this is the preferred route for developement).
For example, if you're using chrome all you need to do is set the allow local file access flag: How to launch html using Chrome at "--allow-file-access-from-files" mode?
In mozilla set the about:config key security.fileuri.strict_origin_policy to false.
Again, these are options for loading local files without a webserver, but setting up a webserver is a relatively simple task that is the most recommended route.
you'll need to run a local server like python's SimpleHTTPServer to get this to work locally. once you've got it installed, it's as simple as running a single command in your terminal.
however, since you said that your end users should be able to access it through the browser, do you mean that you'll host it online? if so, they'll be able to view it correctly on the server
Notice how in the first example the data in hard coded into the html page with the variable name data? The data is already here so you won't need a server to go and fetch the data. On the other hand, in second example the data is not hardcoded and is fetched with a server. If you want this to work like the first example you will have to hard code the data into the web page.
You may want to use SERVED by Ian Johnson, its pretty good.
http://enjalot.github.io/served/

Easiest way to load and read a local text file with javascript?

I have a .csv file that I wish to load that contains information that the .HTML page will format itself with. I'm not sure how to do this however,
Here's a simple image of the files: http://i.imgur.com/GHfrgff.png
I have looked into HTML5's FileReader and it seems like it will get the job done but it seems to require usage of input forms. I just want to load the file and be able to access the text inside and manipulate it as I see fit.
This post mentions AJAX, however the thing is that this webpage will only ever be deployed locally, so it's a bit iffy.
How is this usually done?
Since your web page and data file are in the same directory you can use AJAX to read the data file. However I note from the icons in your image that you are using Chrome. By default Chrome prevents just that feature and reports an access violation. To allow the data file to be read you must have invoked Chrome with a command line option --allow-file-access-from-files.
An alternative, which may work for you, is to use drag the file and drop into onto your web page. Refer to your preferred DOM reference for "drag and drop files".
You can totally make an ajax request to a local file, and get its content back.
If you are using jQuery, take a look at the $.get() function that will return the content of your file in a variable. You just to pass the path of your file in parameter, as you would do for querying a "normal" URL.
You cannot make cross domain ajax requests for security purposes. That's the whole point of having apis. However you can make an api out of the $.get request URL.
The solution is to use YQL (Yahoo Query Language) which is a pretty nifty tool for making api calls out of virtually any website. So then you can easily read the contents of the file and use it.
You might want to look at the official documentation and the YQL Console
I also wrote a blog post specifially for using YQL for cross domain ajax requests. Hope it helps
You can try AJAX (if you do not need asynchronous processing set "async" to false. This version below ran in any browser I tried when employed via a local web server (the address contains "localhost") and the text file was indeed in the UTF-8-format. If you want to start the page via the file system (the address starts with "file"), then Chrome (and likely Safari, too, but not Firefox) generates the "Origin null is not allowed by Access-Control-Allow-Origin."-error mentioned above. See the discussion here.
$.ajax({
async: false,
type: "GET",
url: "./testcsv.csv",
dataType: "text",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
//parse the file content here
}
});
The idea to use script-files which contain the settings as variables mentioned by Phrogz might be a viable option in your scenario, though. I was using files in the "Ini"-format to be changed by users.

Loading JSON from a local HTML5 web app using JavaScript

I am developing a small HTML5 web app, that users can use offline with their browsers, cross-platform. They will receive the wep app on a CD or USB-Stick and double-click the HTML file. The HTML file then loads CSS, JavaScript files etc... all locally from the same directory/subdirectories.
So far, everything is fine. But I want also to load a file (also local, from the very same directory) that contains JSON, and use that data to build part of the DOM.
$.getJSON("playlistcontent.json", function (json) {
//use the data...
});
Here I ran into the famous
Origin null is not allowed by Access-Control-Allow-Origin
error. There are a lot of resources about this, even quite similar questions. But since this is intentionally locally, the proposed solutions do not work.
However, since AJAX is "Asynchronous" I thing there is probably a more "synchronous" or otherwise better approach? What about JSONP?
Note: I know that I can start the browser (especially Chrome) with the security check disabled, but this is not an option for my users.
I answered a similar question here.
You can use HTML5's File API, which includes a FileReader, and then call JSON.parse on the result.
I would use Felix Kling's approach with JSONP. Wrap your data file in in a callback function:
(function(data) {
// Do things with your data object here
})(
// Put your data object here as the argument to the callback
);
When you include this script file with a tag, the callback function will automatically be executed.
I like Felix Kling's approach, if all you need is JSON data, you can just load your data by setting JS variables and load the JSON files using script tags. However, if that's not enough for your needs, you can use a solution like http://www.server2go-web.de/ which will run a webserver from the CD, therefore bypassing the local file restrictions.

How to read contents of a file using javascript?

I have an input type="file" button. After I choose a file, I have to read the contents of the file using javascript. Is it possible to read/get contents of a chosen file using javascript or ajax?
You are all wrong in a way. It is possible. With the new File API you can read files before submitting them to the server. It is not available in all browsers yet though.
Check this example. Try to open a text file for example.
http://development.zeta-two.com/stable/file-api/file.html
Edit: Even though the question states "uploaded file" I interpret it as, "a file to be uploaded". Otherwise it doesn't make sense at all.
With AJAX its possible to read uploaded file but with pure javascript its not possible because javascript works on client side not on sever side.
if you are going to use jquery than Ajax call may be like this
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Reading files client side is hard:
How to read and write into file using JavaScript
Read a local file
Local file access with javascript
Unless you are trying to do it with local javascript:
Access Local Files with Local Javascript
Or server side javascript:
http://en.wikipedia.org/wiki/Server-side_JavaScript
Alternatively you can force your user to install an ActiveX object:
http://4umi.com/web/javascript/fileread.php
you cant do it using javascript directly. You can post the file to the server an then use ajax to retrieve the content.
Javascript is designed not to have access to the computer it is running on. This is so that rogue javascript can't read the user's harddrive.
You could look into using iframes though.
It is not possible to do it in java script. See Local file access with javascript
I agree with DoXicK above. You can post the file first on server and then you can use Ajax to read it.
That is not entirely impossible
A browser's usually runs Javascript(JavaScript Engine) in a sandboxed environment.
So you can use Windows Scripting Host or Internet Explorer in a trusted environment and use the FileSystemObject
or use
Or upload a file to your server and use the XMLHttpRequest object.(in other words - Ajax)
For IE use the FileSystemObject (which is found on all Windows systems).
For Firefox:
var file = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home");
See https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO
To see these methods and others in use, look at TiddlyWiki app to see how it does it across all major browsers.

Categories

Resources