How to load local JSON files in Javascript - javascript

I'm writing a web app (well, actually it will eventually be an OS X Dashboard widget, but I decided to prototype it first as a simple web page) that needs to load some initializing data from a local JSON file. My code looks like this:
function loadDatos() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'datos.json', true);
xobj.onReadyStateChange = function () {
if (xobj.readyState == 4) {
var jsonTexto = xobj.responseText;
ProcessTheData(jsonTexto);
}
}
xobj.send(null);
}
The function get called from an onLoad() event in the HTML file's BODY tag. Now, from what I see when debugging, the function gets executed, but the onReadytStateChange event handler never gets called.
What should I do? I thought it was a bit odd to use a XMLHttpRequest to access a local file, but the new tutorials I've seen that deal with this issue seem to say that it should work (the 99% of docs I've seen talk about how to load JSON from a remote server, not from a local file).
I'm testing using Firefox 3.6.10, but I've also tried with Safari 4.

onreadystatechange property has no capital letters. See: MDC XMLHttpRequest

Unless we add extension .json and MIMETYPE application\json, IIS will throw an error.
See here: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cd72c0dc-c5b8-42e4-96c2-b3c656f99ead.mspx?mfr=true

Related

XMLhttprequest not posting (new to it)

I am trying to send data from javascript to a php page using xmlhttprequests.
It is just like sending form data, eventhough I have copied the examples exactly, it doesnt work.
I know the problem lays with the xmlhttprequest since I have tried sending the same data using an html form with POST and that works fine. So the PHP works.
the errors I get using my code are:
POST http://localhost/thissite/post 404 (Not Found)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
The current file structure I am using equals:
index.php and store.php in the root and than a folder called js with init.js
function sendData() {
var xmlhttp,
url = "http://localhost/thissite/store.php";
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("post", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("sitetarget=/thissite/&buttontarget=firstbutton&amount=2");
}
This function is in my init.js file which is linked on my index.php page.
I have tried changing the used URL to:
store.php
/store.php
./store.php
../store.php
http://localhost/store.php
But I think the URL I use should be correct since that is the url I get send to when I post the form. It is also the same as multiple examples I found in questions posted on here and those users didn't have the same errors as me. This is probably me misunderstanding but I am eager to find out what the problem is with my code before I throw my computer out of the window or pull my last hair out.
Thank you for answering if you do!

How to read a local text file using javascript

I have a button in in view page. On clicking the button an function gets called.In that function am calling another function with location of file as parameter.In the second function i need to read the file specified in the location passed and show the contents in console.What i already tries is below
ReadFile : function(){
this.ReadTextFile("C:\Users\RFRANCIS\Downloads\Inv00008W.txt");
},
ReadTextFile: function(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
But I am getting Access denied error.Please find me to solve this issue or suggest another method.I am testing this in IE11.
In order to access you local drive you need a valid URL for the file which probably looks more like file:///c:/ than what you have but you have a few overlapping issues here:
The url for a local file must start with file:///
You need to understand about escape characters and slashes in Javascript string literals (you need special syntax to express slashes in javascript)
When you fix these you are still going to get CORS security exceptions because (at least chrome) doesn't perceive local files as one domain. (To resolve this you either need to set you chrome up specially or use a proper localhost http-server on your local machine.

Load Local HTML Into Div (Chrome Extension)

I'm not using a framework and I want to implement an architecture whereby a single html file holds the skeleton of my layout, and certain other html snippets are loaded into various divs in that layout. The code is all in the same directory location inside my main extension folder /popup/
I want to build a very simple function to load the locally saved html snippets into the div elements. Here is my first attempt:
function loadView(viewName,destination){
var URL = "/popup/"+viewName;
var client = new XMLHttpRequest();
client.open('GET', URL, false);
client.onreadystatechange = function() {
document.getElementById(destination).innerHTML = client.responseText;
}
client.send();
}
// Example of a call
loadView('contact.html','widgetBox');
Obviously this is terrible because it relies on setting the ajax to asynch false. But under this solution, that is necessary because the next line of code in the script may/does try to manipulate the newly loaded content.
What would be a method for reaching a similar result, that does not depend on ajax? (or at least, which would resolve the need to use asynch false)
Notes:
I know that there are frameworks for basically this exact problem. I like to learn how to do things without frameworks. I am not challenging the use of frameworks, I'm just not interested in those approaches in this question. Relatedly, I'd like to avoid using jquery (and as this is a chrome extension, developing in clean JS isn't particularly painful).
The content of contact.html is some html, is just a string of html, (i.e. it does not have a header or any content besides that which I seek to load). I am open to another convention besides discrete .html files, but I like this convention as it is easy to keep my various page chunks organized, and keeping them as .html files allows me to read them easily in things that format html nicely.
You should have your loadView function accept a callback as a third parameter. Then, call it when the Ajax call completes. That way, you can use an async request.
function loadView(viewName, destination, callback){
var URL = "/popup/"+viewName;
var client = new XMLHttpRequest();
client.open('GET', URL);
client.onreadystatechange = function() {
if (client.readyState < 4) return; // Wait until the request completes
document.getElementById(destination).innerHTML = client.responseText;
callback();
}
client.send();
}
// Example of a call
loadView('contact.html', 'widgetBox', function() {
// Do whatever comes next
});

Request plain text file in javascript from URL?

I started a blog recently and coded it by hand. It is a static, CSS/HTML5 website. Upon sharing it with friends, I realized that when I would update it via FTP, it would be cached already by their browsers. I decided that I would keep all of my blog posts on new pages and then create a landing page that would somehow determine the newest post and forward users there after they clicked an enter button or something like that.
I was able to create a button that could forward them to a specific link, but I want to create a script that will always forward them to the newest page. So I created a file called 'getLatest.json' and uploaded it to an 'api' subfolder of my site. I then tried to use an XMLHttpRequest to load it:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
window.location = "http://latestBlogPost.com" +
xhttp.responseText.today;
//Today is a parent in the object returned.
}
};
xhttp.open("POST", "http://myWebsite.com/api/getLatest.json", true);
xhttp.send();
}
But that didn't work. The response was a null string. I tried using jquery to no avail.
I tried uploading a file called getLatest.html which contained the url in plaintext. That didn't work either.
tl;dr: Is there some way that I can get plaintext from a URL's html content?
edit: getLatest.json and getLatest.html contain a link to the newest blog post.
There are couple of ways to do this.
First your code is not working because you are using a "POST" it should be "GET", if you do that it will work.
Second easiest way is to create a java script file with variable declared and reference that file to your website
<script type="text/javascript" src="http://your javascript file"> </script>
This file contains your variable like this
var latestBlog = "http://....";
in your code use this variable. No more code required. but as i mentioned earlier if you change your HTTP Verb to get your code will work

Load local XML file with IE 11

I am working on a simple project which involves loading local .xml file into DOM structure by local .html file. We can assume that .html and .xml file are placed in the same folder on the same computer. Problem is that IE 11 disallows any interaction with local xml file. (SCRIPT5: Access is denied.)
So far i tried this solutions (Solution 1,2 are tested and functional within Mozilla FireFox and Google Chrome, Microsoft Edge has some different problem - see first code snippet):
Synchronous/Asynchronous XMLHttpRequest (async in example)
function loadXMLDoc(doc)
{
try{
xmlhttp = new XMLHttpRequest();
}catch(e){
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(e){
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
}
catch(e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
alert("XMLHTTP Not Supported On Your Browser");
}
}
}
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) /*Microsoft edge returns status 0 here */
{
alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET",doc,true);/*IE11 prints "SCRIPT5: Access is denied." into console*/
xmlhttp.send();
}
And JQuery async solution
window.onload = function() {
$.ajax({
url: "output.xml",
aync: true,
success: myHandle,
isLocal:true,
dataType: "xml"
});
}
function myHandle(data) {
alert(data);
}
Third solution consists of simple node.js webserver (see Using node.js as a simple web server)
but this seems to be a too large gun for me.
Also there is a problem that web server has to be start explicitly via cmd / script, but i just want to hit .html and see interpreted xml data.
TL;DR My questions are:
Is there any workaround that makes local .xml files accessible for
IE11?
Why is this "security risk" for IE but not for others?
Note:
Since .xml file can have more Mb, async solutions are prefered for me.
Thank you.
If you're trying to provide the file path as a local path, then it won't work in other browsers as well, using plain javascript, and you may get Cross domain errors. If you have a web server, you can put the file there in the appropriate location, and provide the path as "http://localhost/.../file.xml". This may help.
Well, what I propose as a backup opportunity is to go away a bit from the html + js solution and try XML + XSLT. This should not have any security issues, the only thing that changes for you - you don't need to open index.html but you'll need to open output.xml in your browser.
Also, you would need to add to your XML file the pointer to your XSLT file, see e.g. here how to do that.
Once you loaded your XML and processed it with XSLT you have the same HTML with the same JavaScript, but all data is already rendered. XSLT is quite powerful and I am sure it will fulfill all your requirements

Categories

Resources