Javascript GET file in enclosing folder - javascript

I'm trying to get the JSON contents of a file via JSON, but I can't get it to work. My file tree looks like this:
root
js
script.js
json
data.json
I can't reach the data.json file from my Javascript script. Here's my code:
var data, request;
if (window.XMLHttpRequest){
request = new XMLHttpRequest();
} else {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', '../json/data.json'); // This works fine when the script is placed in the root and the ../ is removed, but when I move it into the js folder it breaks.
request.onreadystatechange = function() {
if ((request.readyState == 4) && (request.status==200)) {
var data = JSON.parse(request.responseText);
if (data) {
return data;
} else {
return "No data found";
}
}
}
request.send();
console.log(data);
The expected result is it returns an object from the JSON folder or print "No data found". Instead I just get undefined in my console. This means my only problem is actually finding that file. I don't normally use JavaScript so I'm probably just not using the right syntax, but since ../json/data.json clearly is incorrect, what is?

Related

Javascript Will not return Contents of JSON File stored

I am working on a small script that is supposed to take information from a JSON file and use that info to populate a table in my webpage. I am writing a script from a Youtube tutorial here, below is the code I have as given in the tutorial:
<script type="text/javascript">
const rankingsBody = document.querySelector("#rankings-table > tbody");
function loadRankings() {
const request = new XMLHttpRequest();
request.open("get", "data/rankings.json");
request.onload = () => {
try {
const json = JSON.parse(request.responseText);
populateRankings(json);
} catch (e) {
console.warn("Could not load rankings");
}
};
request.send();
}
function populateRankings (json) {
console.log(json);
}
console.log(request);
</script>
Now, the console.log() function at the end of the script is supposed to print the contents of the JSON file to the console, upon checking in Firefox, it does not print and throws the following error error:
ReferenceError: request is not defined
And when I try to run the loadRankings function in the console, it says it is undefined, So, I guess its not returning the data as expected because it hasn't been defined?
I am not really sure what the problem could be, could you help me to figure this one out? Thanks in advance guys.
You declared request in loadRankings(). Then you tried to print it outside of the context where it exists with console.log(request); const declarations are not hoisted, so you get a reference error. Either move the declaration to the global scope like this so it's visible to your console.log() statement:
const rankingsBody = document.querySelector("#rankings-table > tbody");
let globalRequest;
function loadRankings() {
const request = new XMLHttpRequest();
// Expose the most recent request in the global variable
globalRequest = request;
request.open("get", "data/rankings.json");
request.onload = () => {
try {
const json = JSON.parse(request.responseText);
populateRankings(json);
} catch (e) {
console.warn("Could not load rankings");
}
};
request.send();
}
function populateRankings (json) {
console.log(json);
}
console.log(globalRequest);
or just remove the console.log() statement entirely.

Load JSON, YAML, and XML files in a Singleton Pattern

I am trying to implement a ConfigLoader that loads YAML, XML, and JSON files in a singleton method, i just got started but got stuck in terms of where else to go, and how to load a YAML file
heres what I have so far, i need some insights on how to translate this into a singleton pattern, and some insights on how to load a YAML file
let getXMLFile = function(path, callback) {
//create new object
let request = new XMLHttpRequest();
//open the object and specify verb and file path
request.open("GET", path);
//set header of httprequest
request.setrequestHeader("Content-Type","text/xml");
//set event listener
request.onReadystatechange= function(){
//check to see ready state and event status
if (request.readyState === 4 && request.status === 200){
callback(request.responseXML);
}
};
request.send();
};
getXMLFile("fileName.xml", function(xml){
console.log(xml);
});
"use strict";
//Loading Json File with fetch
//using URL and http
//use request object to define key
let myRequest = new Request("./data_class.json")
//pass request object
fetch(myRequest).then(function(resp){
//return response but act on it with Json method
//convert text to json file
return resp.json();
})
//handle JSON data
.then(function(data){
console.log(data);
});

Getting xmlhttp response empty when json object accessed through server path

I have a js function which goes to a spring controller class returning a json object with data like :
{"prop1":"val1",
"prop2":"val2"}
The js function is something like :
accessValue(a,b,c){
var xmlhttp = new XMLHttpRequest();
alert("This works 1");
xmlhttp.onreadystatechange = function() {
alert("This works 2");
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert("This works 3" + xmlhttp.status);//line 1
if (xmlhttp.status == 200) {
var jsonobj = JSON.parse(this.responseText); //line 1
alert("Hi ");
document.getElementById(b).innerHTML = jsonobj.prop1;
document.getElementById(c).innerHTML = jsonobj.prop2;
console.log(jsonobj.prop2);
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
}
};
xmlhttp.open("GET", a + "--spring controller class path --");
xmlhttp.send(null);
}
In the function parameters b and c are div ids which I want to update with the data which comes in the json object. Parameter a is a URL which is appended with spring path of the controller class, this class returns json object which runs perfectly fine.
At line 1, I am getting status for xmlhttp.status as 0 which is empty response. After searching online I found out that this may happen bcz the file may be accessed locally properly but through server its not happening. The same code when used on localhost works great. Is there a way I could access this spring controller returned json object on server using proper http url and parse the data to update my divs ?

How to load 2 json with nodejs

I want to load 2 json files:
number.json : {"argent":300,"nbJoueur":11,"nbClub":1,"nbVictoire":0,"nbDefaite":0}
img.json : {"bonus1":false,"bonus2":false,"bonus3":false,"bonus4":false,"bonus5":false,"bonus6":false}
I managed to read the first file, but I don't know what to do to read the second file in the same time.
I have this code :
Javascript :
function load(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
var recup = JSON.parse(this.responseText);
number["argent"] = recup["argent"];
number["nbJoueur"] = recup["nbJoueur"];
number["nbClub"] = recup["nbClub"];
number["nbVictoire"] = recup["nbVictoire"];
number["nbDefaite"] = recup["nbDefaite"];
}
};
xhr.open("GET","http://localhost:8080/load",true);
xhr.send();
}
Nodejs :
function load(response){
console.log("Load called");
fs.readFile("number.json", function(err,data){
if(err) {
throw err;
response.setHeader("Access-Control-Allow-Origin","*");
response.writeHead(418);
response.end();
}
else{
response.setHeader("Access-Control-Allow-Origin","*");
response.writeHead(200);
response.write(data);
response.end();
}
});
}
Based on this answer, you can get your json file simply that way:
var json = require('path1.json');
var json2 = require('path2.json')
And then you can use the variables in your response callback
You've written a hardcoded handler that can only serve one file.
Instead, you could:
write a general handler that serves either file depending upon the url that's accessed.
Duplicate the load function and create a new path for the second file
Or, if your JSON files aren't going to change frequently, you can put them in a folder and serve it static
Edit: I noticed you aren't using any framework, so I removed my code sample that corresponds to the Express framework.

AJAX and Javascript not working

NO JQUERY. I am using peoplecode which is similar to JSP, ASP, and ZXZ. The ajax request is triggered am I am trying to pull the text 'Hello World' from this script...
Function IScript_AJAX_Test()
%Response.Write("<div id='hello'>Hello World</div>");
End-Function;
My javascript function that makes the ajax call looks like this...
function AJAX_test (ajax_link) {
if (typeof XMLHttpRequest == 'undefined') {
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.');
};
}
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
document.getElementById('ajax').innerHTML = request.responseText.document.getElementById('hello').innerHTML;
//document.getElementById('ajax').innerHTML = 'Testing';
}
}
request.open('GET', ajax_link, true);
request.send();
//document.getElementById('ajax').innerHTML = ajax_link;
}
As you can see in this line..
document.getElementById('ajax').innerHTML = request.responseText.document.getElementById('hello').innerHTML;
...I am trying to grab the text by getting the innerHTML from the id. This isn't working though. When I click the button nothing happens.
I tried using the line below, but it returns an entire new page where the id would be (probably because of Peoplesoft)...
document.getElementById('ajax').innerHTML = request.responseText;
Can someone help me achieve this...
I tried your code and it works for me, with
Function IScript_AJAX_Test()
%Response.Write("<div id='hello'>Hello World");
End-Function;
and in the javascript
document.getElementById('ajax').innerHTML = request.responseText;
Make sure you call the content servlet (psc), not the portal servlet (psp), e.g.
'http://peoplesofturl/psc/ps/EMPLOYEE/HRMS/s/WEBLIB_Z_SYS.FUNCLIB.FieldFormula.IScript_AJAX_Test', otherwise you'll get the response wrapped in the peoplesoft portal.
You can generate the url from peoplecode with the GenerateScriptContentRelURL or GenerateScriptContentURL functions.
Make it simple:
Function IScript_AJAX_Test()
%Response.Write("Hello World");
End-Function;
Javascript:
document.getElementById('ajax').innerHTML = request.responseText;
Ajax might be two types. One is server-side and the other one is client-side. You are trying to get data from client side. In this case ajax fetch nothing but the whole page result of a page not a portion. You will have the whole page result(HTML output) if you write
document.getElementById('ajax').innerHTML = request.responseText;
But you cannot fetch just only the innerHtml part of certain portion of another page. On that case you will get the whole page.

Categories

Resources