Easiest way to load and read a local text file with javascript? - 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.

Related

jQuery-media only fetches external content

I am using the jQuery media plugin to display HTML and PDF documents on my webpage. The plugin will load any externally hosted PDF/HTML with no issues. However, when I try to provide a URL to my application which returns the file content, it never attempts to fetch the URL.
I have tried a relative URL path (/ajax/...) and a full URL path (protocol, port & all) to the app view.
I have tested the URL I want the application to call by providing the URL to the browser and it properly returns the PDF document.
Anyone have an idea to force the plugin to fetch the URL I am providing?
So after rewriting the jquery.media plugin due to its complex nature, Greg and I found the solution. Effectively, the extension type must be specified in the url. For example the url '/mypdfs/my.pdf' would work but the url 'mypdfs/123' will not because jquery.media cannot determine the file type. A way to get around this is to make an ajax HEAD request and get the content type and then pass the appropriate extension type as an option to the media call.
$.ajax({
type: "HEAD",
async: true,
url: "http://myurl.com/file",
success: function(message, text, response){
var contentType = response.getResponseHeader('Content-Type');
// Map content types to extension type
$('.media').media({type: extensionType});
}
});
Also, Malsup's library seems to be unmaintained. We did a rewrite of the library which can currently be found here. We will be adding mapping Content-Type to file extensions as time permits so that this can be more flexibly implemented. Feel free to make a pull request.

Looking for a way to scrape HTML with JS

As the title suggests, I'm looking for a hopefully straightforward way of scraping all of the HTML from a webpage. Storing it in a string perhaps, and then navigating through that string to pull out the desired element.
Specifically, I want to scrape my twitter page and display my profile picture inside a new div. I know there are several tools for doing just this, but I would anyone have some code examples or suggestions for how I might do this myself?
Thanks a lot
UPDATE
After a very helpful response from T.J. Crowder I did some more searching online and found this resource.
In theory, this is easy. You just do an ajax call to get the text of the page, then use jQuery to turn that into a disconnected DOM, and then use all the usual jQuery tools to find and extract what you need.
$.ajax({
url: "http://example.com/some/path",
success: function(html) {
var tree = $(html);
var imgsrc = tree.find("img.some-class").attr("src");
if (imgsrc) {
// ...add the image to your page
}
}
});
But (and it's a big one) it's not likely to work, because of the Same Origin Policy, which prevents cross-origin ajax calls. Certain individual sites may have an open CORS policy, but most won't, and of course supporting CORS on IE8 and IE9 requires an extra jQuery plug-in.
So to do this with sites that don't allow your origin via CORS, there must be a server involved. It can be your server and you can grab the text of the page you want using server-side code and then send it to your page via ajax (or just build the bits you want into your page when you first render it). All of the usual server-side stacks (PHP, Node, ASP.Net, JVM, ...) have the ability to grab web pages. Or, in some cases, you may be able to use YQL as a cross-domain proxy, using their server rather than your own.

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.

jquery load to hide content

There is javascript on my webpage, but I need to hide it from my users (I don't want them to be able to see it because it contains some answers to the game.)
So I tried using Jquery .load in order to hide the content (I load the content from an external js file with that call). But it failed to load. So I tried ajax and it failed too.
Maybe the problem comes from the fact that I'm trying to load a file located in my root directory, while the original page is located in "root/public_html/main/pages":
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url : "../../../secret_code.js",
dataType: "text",
success : function (data) {
$("#ajaxcontent").html(data);
}
});
});
</script>
1) Why can't I load a file from the root directory with ajax or load method?
2) Is there another way around?
PS: I'm putting the file in the root directory so people can't access it directly from their browsers...
1) if the file isn't accessible via web browsers, than it's not accessible via ajax (ajax is part of the web browsers
2) try /secret_code instead of ../../../secret_code.js
What is your system setup? Are you using a CMS?
Even if you add the javascript to the page after page load a user with a tool like firebug can go and view it. I don't think what you are doing is really going to secure it. An alternate solution is that you could minify and obfuscate the javascript that you use in your production environment. This will produce near unreadable but functioning javascript code. There are a number of tools that you can run your code through to minify and obfuscate it. Here is one tool you could use: http://www.refresh-sf.com/yui/
If that isn't enough then maybe you could put the answers to the game on your serverside and pull them via ajax. I don't know your setup so I don't know if that is viable for you.
Navigate to the URL, not the directory. Like
$.ajax({
url : "http://domain.com/js/secret_code.js",
..
Even if you load your content dynamicly, it's quite easy to see content of the file using firebug, fiddler or any kind of proxy. I suggest you to use obfuscator. It will be harder for user to find answer
Take a look at the jQuery.getScript() function, it's designed for loading Javascript files over AJAX and should do what you need.
Try jQuery's $.getScript() method for loading external
Script files, however, you can easily see the contents of the script file using Firebug or the developer toolbar!
Security first
You can't access your root directory with JavaScript because people would read out your database passwords, ftp password aso. if that would be possible.
You can only load files that are accessible directly from browsers, for example, http://www.mydomain.com/secret_code.js
If it can't be accessed directly by the browser, it can't be accessed by the browser via ajax. You can however use .htaccess to prevent users from opening up a js file directly, though that doesn't keep them from looking at it in the google chrome or firebug consoles.
If you want to keep it secret, don't let it get to the browser.

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