JSON file cannot be found in javascript - javascript

I am attempting to load a JSON file from javascript but i keep getting the following error even though the path is correct
[HTTP/1.1 404 Not Found 2ms]
this is the code i am using to load it
loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'Assets/test.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == 200) {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
window.onload = function () {
var canvas = <HTMLCanvasElement> document.getElementById('Can');
context = canvas.getContext('2d');
load = new preload.AtlasLoader();
load.loadJSON(init);
}
function init(response) {
image2 = JSON.parse(response);
}
thanks in advance

i found the answer in this thread:
https://stackoverflow.com/questions/19516829/allow-loading-of-json-files-in-visual-studio-express-2013-for-web
it was a configuration issue with IIS and you just need to add the lnes posted in the answer in that question.

Related

assign variable to ajax responseText [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm trying to load the text content of a file into a variable using ajax.
The function readFile() seems to works fine. I think the issue is that my file, 'countries.csv' is big and taking too long to load, so console.log(x) just returns 'undefined'
// last argument in open() is async; must be true or else chrome gives an error
function readFile(file) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file, true);
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
var fileContent = xhr.responseText;
// console.log(fileContent); <-- this line would work just fine
return fileContent;
}
}
xhr.send(null);
}
// so this next line takes some time to run
var x = readFile('/data/countries.csv');
// and this line runs before the last line is done
console.log(x);
What can I do to load the content of the file 'countries.csv' into the variable x before I start actually working with the variable x?
Am I missing some kind of event listener?
You need to pass a callback :)
Try
function readFile(file, cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file, true);
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
var fileContent = xhr.responseText;
return cb(fileContent);
}
}
xhr.send(null);
}
readFile('/data/countries.csv', thing => console.log(thing));
Here's some extra stuff to learn more about callback/async programming in javascript: http://www.learn-js.org/en/Callbacks

How to validate the existence of a JSON file before load it with the XMLHttpRequest Javascript object?

I am working loading a JSON file from a relative local path into my web based app. To do this I am using an XMLHttpRequest object, as following:
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'myFyle.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
}
xobj.send(null);
My issue is that I can't manage the browser error (net::ERR_FILE_NOT_FOUND) when myFyle.json is not found. I would like to load an standard .json file (e.g. myStandardFile.json) when this happens.
Does anybody has an idea to do this?
Thanks in advance!
Pedro.
You can use xobj.status === 404 to detect 'file not found'.
The web site hosting server will typically generate a "404 Not Found"
web page when a user attempts to follow a broken or dead link;
In case of 404 you can load your default file like this:
function load(file, callback) {
var defaultFile = "myStandardFile.json";
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function() {
if (xobj.readyState !== 4) return true;
if (xobj.status === 200) {
callback(JSON.parse(xobj.responseText));
//File not found.
//The second condition just to prevent endless calls
//in case if your default file doesn't exist
} else if (xobj.status === 404 && file !== defaultFile) {
load(defaultFile, callback);
}
}
xobj.send(null);
}
load("myFyle.json", function(data) {
console.log(data);
})
Demo:
function load(file, callback) {
var defaultFile = "https://httpbin.org/user-agent";
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function() {
if (xobj.readyState !== 4) return true;
if (xobj.status === 200) {
callback(JSON.parse(xobj.responseText));
//File not found
} else if (xobj.status === 404 && file !== defaultFile) {
load(defaultFile, callback);
}
}
xobj.send(null);
}
load("https://httpbin.org/inexistentFile.json", function(data) {
console.log(data);
})
I hope this will help you.

Check if image exists without error message

Through (native) javascript, i want to check if an image exists. I have found this script:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
from this question. However, everytime i run this, it throws me a HEAD error message whenever it does not find an image (in the console). Can i get rid of this error whenever it fails to find something?
The onload/onerror solution in the comments at the linked question also give me the same issue, with reporting errors.
Try this
function imageExists(url, callback) {
var img = new Image();
img.onload = function() { callback(true); };
img.onerror = function() { callback(false); };
img.src = url;
}
// Sample usage
var imageUrl = 'image_url';
imageExists(imageUrl, function(exists) {
alert(exists);
});
check out Checking if image does exists using javascript

AJAX, pass additional variable to callback and store XMLHTTLRequest.response to variable

I am trying to read a local file on the server with a standard function loadDoc(url, cfunc), then
1) search for a particular string in the file (getLine());
2) if possible, store that line to a variable.
For point 1 I pass a string to the callback.
2) Getting the response is problematic because XMLHTTPRequest is asynchronous. At this moment the error is:
"ReferenceError: xhttp is not defined"
function main(){
var url="data.txt"
var str="1,0,"; //just an example
var myCallBackWithVar = function(){
getLine(str);
};
loadDoc(url, myCallBackWithVar);
//Can I get the line here somehow?
}
function loadDoc(url, cfunc) {
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cfunc(xhttp);
}
}
xhttp.overrideMimeType('text/plain');
xhttp.open("GET", url, true);
xhttp.send();
}
//Find string with the desired data in txt file
function getLine(str) {
var data=xhttp.responseText;
//Find the line from the txt file
var start=data.indexOf(str);
var end=data.indexOf(";",start);
var line=data.substring(start,end);
return line;
}
data.txt is something like this:
some data here
0,0,9;
1,0,10;
1,1,11;
I have already tried to pass the XMLHTTPRequest objetct getLine(xhttp,str). How to solve points 1 and 2? I'd rather keep it jQuery free for the moment. Thanks
Can I get the line here somehow?
I don't think that's a good idea. You can't be sure that your app will work correctly. XHR is a async function and you should use async architecture.
Here the example how this functionality can be done.
var text; // define global variable
var str = "1,0,"; //just an example
function main(){
var url = "data.txt";
var cb = function (data){
text = getLine(data);
// you can use text var here
// or in anyewhere in your code
}
loadDoc(url, cb);
}
function loadDoc(url, cb) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
cb(xhr.responseText);
}
}
xhr.overrideMimeType('text/plain');
xhr.open("GET", url, true);
xhr.send();
}
//Find string with the desired data in txt file
function getLine(data) {
if(data) {
//Find the line from the txt file
var start = data.indexOf(str);
var end = data.indexOf(";", start);
var line = data.substring(start, end);
return line;
}
}
On complete, you don't need to pass the whole xhttp variable through too the callback function. When you do this:
function getLine(str) {
var data=xhttp.responseText;
xhttp is already out of scope. To fix this, the parameter name would also have to be xhttp.
A better way would be to do :
cfunc(xhttp.responseText);
and then
var data=str
This way, you are passing only what you need as an argument.

JSON Parse File Path

I'm stuck trying to get the correct path to the local file. I have the following directories:
Resources ->
data ->
file.json
js ->
folder ->
script.js
html ->
folder ->
file1.html
I'm executing script.js from file1.html, with js code:
var answers = JSON.parse('../../data/file.json');
alert(answers);
But it doesn't work, even alert is not starting.
What is wrong?
Also I've tried this:
function readJSON(file) {
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
if (request.status == 200)
return request.responseText;
};
var temp = readJSON('../../data/file.json');
alert(temp);
Alert undefined in this case.
Since it is in the directory data/, You need to do:
file path is '../../data/file.json'
$.getJSON('../../data/file.json', function(data) {
alert(data);
});
Pure JS:
var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
alert (my_JSON_object.result[0]);
This solution uses an Asynchronous call. It will likely work better than a synchronous solution.
var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null);
request.onreadystatechange = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var my_JSON_object = JSON.parse(request.responseText);
console.log(my_JSON_object);
}
}
Loading local JSON file
Use something like this
$.getJSON("../../data/file.json", function(json) {
console.log(json); // this will show the info in firebug console
alert(json);
});
var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);
This code worked for me.
If Resources is the root path, best way to access file.json would be via /data/file.json
My case of working code is:
var request = new XMLHttpRequest();
request.open("GET", "<path_to_file>", false);
request.overrideMimeType("application/json");
request.send(null);
var jsonData = JSON.parse(request.responseText);
console.log(jsonData);
Even if long time answerd, I here is another that does not need to create a request. I created a lg.js script containing a class and some functions (setLg, de, en, ...)
Each "lg" function (de, en, fr, ...) provides a json object containing the translations.
"use strict"
class Lg {
constructor() { this.tr = this.en(); }
setLg(l) {
if l == "de" this.tr = this.de();
if l == "en" this.tr = this.en();
de() {
"item": "Artikel",
"login": "Login"
}
en() {
"item": "Item",
"login": "login"
}
}
var lg = new Lg(); //global accessable object
You can then use it by "lg.tr.item"
You could also create a small function, that checks if the "key" is in the JSON object to have some kind of error checking.

Categories

Resources