Get JSON from local JavaScript - javascript

good afternoon. I'm developing an app that can get a JSON from local (manifest.json). I want to get this file from JavaScript and then read it. But I have a problem, I cant call this file. How can I?
var urlJSON = new XMLHttpRequest("manifes.json").toString;
var dataJSON = JSON.parse(urlJSON);
alert(dataJSON.name);

var xmlhttp = new XMLHttpRequest();
var url = 'manifest.json';
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(JSON.parse(xmlhttp.responseText));
}
if (xmlhttp.status == 404) {}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
Or run chrome with arguments --allow-file-access-from-files
Or download and create server for your app

Related

XMLHttpRequest Replace Element Won't Work With LocalStorage

I tried to implement cookie logging with localStorage into the javascript code for replacing a specific element. It uses the XMLHttprequest method and, I got no idea why it won't work with localStorage. Please enlighten me.
localStorage.setItem("replace1", this.JSON.parse(responseText));
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");
}
};
xhttp.open("GET", "yoinkexecutor2.php", true);
xhttp.send();
}
You can only display data when the async operation (GET) request terminates.
Otherwise you'll get undefined since nothing exits in the localStorage under that key
Also, you can only store strings in local storage, meaning you need to parse that object string once you want to retrieve the data using getItem
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
localStorage.setItem("replace1", JSON.stringify(this.responseText))
document.getElementById("replace1").innerHTML = JSON.parse(localStorage.getItem("replace1"))
}
};
xhttp.open("GET", "yoinkexecutor2.php", true);
xhttp.send();
}

How to link JSON file so that it can be parsed and used to create an arraylist

I would like my program to import an JSON file, using the data to create an array-list then access the array-list so that I can display it on the web page.
I've tried using JSON.parse() but it only works when I do something like JSON.parse('[{"shape":"polygon"},{"shape":"square"}]); It doesn't work for parsing a JSON file that is not declared inside. My JSON file is saved to my desktop. I'm new to JavaScript and importing files so anything would be helpful!
I've tried using:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObject = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", "PATIENT51.txt", true);
xmlhttp.send();
I keep getting errors with: JSON.parse(this.responseText);
JSON.parse Error: Invalid character at position:5 problemlist1.html(3,5)
You can just have the log in xmlhttp scope and it'll work.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.responseText))
}
};
xmlhttp.open("GET", "PATIENT51.txt", true);
xmlhttp.send();
EDIT: seen your edit, in addition, make sure that your JSON has the right format:
{
"key1" : 1,
"key2" : 2,
"key3" : 3
}

Why can't separate the function for xmlHttp.onreadystatechange?

The below js file test.js` works fine in my html.
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
Now i want to separate them
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
in a single function.
I rewrite the test1.js as test2.js.
var xmlHttp;
function ready(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = ready;
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
The test2.js encounter error info:
test2.js:4 Uncaught TypeError: Cannot read property 'readyState' of undefined
at XMLHttpRequest.ready (test2.js:4)
Another issue :what is the right order for the following statements?
I have seen some material write them as below :
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){ }
Other material also seen:
xmlHttp.onreadystatechange = function(){ }
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
And other order in webpage xmlHttp statements order
xmlhttp.open("POST", "Demo", true);
xmlhttp.onreadystatechange=myCallBack;
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send("FirstName=Nat&LastName=Dunn");
In sendData you have:
var xmlHttp = new XMLHttpRequest();
Your only mistake is including the var here - just do this instead:
xmlHttp = new XMLHttpRequest();
The reason this matters is that the var is declaring a new local variable of the same name, which is then getting assigned to - so ready doesn't get access to it. It accesses the global xmlHttp variable, which is never assigned to. By removing the var as shown above, you ensure that the global variable is assigned to - and this should work. (Although of course it's not best practice to use globals.)

NodeJS XMLHttpRequest response

I'm making and app and I need do get the number of verses of a chapter of the bible.
I'm getting the info from http://www.kingjamesbibleonline.org/
In order to do that I am making an XMLHttpRequest to send to the server from the function getVerses() from the site.
The problem that I am facing is that I'm not getting a .responseText from the XMLHttpRequest. When I use firebug and call that function, in the Network tab > Response tab I get nothing but on Network tab > Preview I get the answer.
Where is this answer coming from and what is the variable that has this value?
My node code is as follows:
let XMLHttpRequest2 = require("xmlhttprequest").XMLHttpRequest;
function getVerses() {
let xmlhttp = new XMLHttpRequest2(); //: new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == xmlhttp.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) { }
else { }
}
}
xmlhttp.open("POST", "http://www.kingjamesbibleonline.org/ajax.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('callFunc=getMaxVerseForChapter&book='+'"Genesis"'+'&chapter='+'"2"');
}
getVerses();
Apparently the server is very strict and it expects the header to be called Content-Type and not Content-type. Some kind of poorly written stuff obviously (in PHP). Also get rid of the double quotes around the values you are sending.
Here you go:
let XMLHttpRequest2 = require("xmlhttprequest").XMLHttpRequest;
function getVerses() {
let xmlhttp = new XMLHttpRequest2(); //: new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == xmlhttp.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) { }
else { }
}
}
xmlhttp.open("POST", "http://www.kingjamesbibleonline.org/ajax.php", true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send('callFunc=getMaxVerseForChapter&book=' + 'Genesis' + '&chapter=' + '2');
}
getVerses();
and since you are hardcoding the values, you don't really need string concatenation:
xmlhttp.send('callFunc=getMaxVerseForChapter&book=Genesis&chapter=2);

xmlhttp.open multiple XML files

How would I go about fetching multiple XML files? I tried creating an array but that only opens the last file, and as I understand it xmlhttp.open is supposed to cancel any previous send. I tried modifying this which was the closest thing I could find, but my JavaScript knowledge is a bit to limited to adapt it.
This is the basic code I'm using to get one XML file.
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","myfile.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("TAGNAME");
for (i=0;i<x.length;i++)
{ // Further parsing
}
Also is it possible to then display which file the parsed content comes from in my loop?
try this:
var arr = ["file1.xml", "file2.xml"],
cnt = 0, xhr = new XMLHttpRequest(), method = "GET";
function formatXml(file, xmlDoc) {
var x=xmlDoc.getElementsByTagName("TAGNAME");
console.log(file,x);
}
function getXml() {
xhr.open(method, arr[cnt], true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
formatXml(arr[cnt], xhr.responseText);
cnt++;
if (cnt < arr.length) getXml(); // call again
}
};
xhr.send();
}
getXml(); // start it

Categories

Resources