This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I've searched for an answer for my particular predicament and I reckon it must have something to do with misunderstandings of my own (I'm new to JS). I know of similar topics but not quite addressing what I'd like to pin down - please forgive me if I have missed something previously posted.
I have boiled down what I'm trying to do to the following JavaScript which draws on jQuery's get to read file contents to a variable (I was trying to avoid all the hullabaloo involved in using XMLHttpRequest() just to read a file server-side):
window.onload = function(){
var refFile = "./myFile"; // path to my txt file
var fileContent;
$.get(refFile, function(response) {
fileContent = response;
alert(fileContent); // I get data here just fine
});
alert(fileContent); // undefined here - how can I have fileContent defined here?
}
If it's preferable to use XMLHttpRequest in pure JS instead that's fine, but I'd just like to know how to be able to make the value live outside the retrieving function - for use with other functions, for instance.
Any ideas on what I'm missing?
Any help would be much appreciated.
The $.get() function works asynchronous, so the fileContent doesn't contain the response because of this.
window.onload = function(){
var refFile = "./myFile"; // path to my txt file
var fileContent;
$.get(refFile, function(response) {
// do something here
}).done(function(response){
fileContent = response;
});
alert(fileContent); // not undefined anymore
}
Take a look at the documentation
This code should work for you.
var refFile = "./myfile"; // path to my txt file
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(readBody(xhr));
}
}
xhr.open('GET', refFile, true);
xhr.send(null);
Related
This question already has answers here:
How can I open a JSON file in JavaScript without jQuery?
(5 answers)
Closed 12 months ago.
So, i'm trying to run this code to put the information from the JSON file to the HTML page. This is the code im trying to run:
HTML:
<div id="gameContainer">
<script>
var games = "../games.json"
document.getElementById("gameContainer").innerHTML = `<h1>${games.author}</h1>`
</script>
</div>
games.json:
[
{
"name": "gameName",
"author": "authorName"
}
]
On the site, the html says "undefined" and that's it. No errors in the console, nothin.
You will have to fetch the file first in order to read the contents of the file.
const url = '../games.json';
const fetchJson = async () => {
try {
const data = await fetch(url);
const response = await data.json();
document.getElementById('gameContainer').innerHTML = `<h1>${response[0].author}</h1>`;
}
catch (error) {
console.log(error);
}
};
also, your games is an Array! So you need to use an Array index in order to then get the containing Object like: games[0].author, not games.author.
You cannot make a AJAX call to a local resource as the request is made using HTTP.
A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.
In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():
http://api.jquery.com/jQuery.getJSON
Here's a way to do it without jQuery.
First create this function:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '../news_data.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(JSON.parse(xobj.responseText));
}
};
xobj.send(null);
}
Then you can use it by simply calling something like this:
loadJSON(function(json) {
console.log(json); // this will log out the json object
});
source
Hello I need some help i am new learning so well the question might be a little silly but anyways I am tired of search everywhere and not able to find the answer I need.
So basically I have this json located at http://swapi.co/api/people/1/?format=json
and I have this function in javascript:
function get_data_api()
{
var data = anything_in_http://swapi.co/api/people/1/?format=json
alert("name_of_json_from_url")
}
So what I am trying to is to assign to that var data everything cotained in the json URL and then fetched to every tag and show them in an alert.
Hope it makes sense!
This is a JavaScript implementation you don't need JQuery
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var readyState = xhr.readyState;
var status = xhr.status;
if (readyState == 4 && status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('http://swapi.co/api/people/1/?format=json',
function(err, data) {
if (err != null) {
alert('You have an error: ' + err);
} else {
console.log(data);
alert('The name from the URL: ' + data.name);
}
});
You can use jQuery http://api.jquery.com/jquery.getjson/
var jqxhr = $.getJSON( "http://swapi.co/api/people/1/?format=json", function() {
console.log( "success" );
})
.done(function(data) {
console.log( data.name );
});
This is a possible duplicate of How to get JSON from URL in Javascript?
which is the first result on google with keyword "javascript json from url" maybe you were using a wrong keywords for searching
Extra info: How to add jQuery to your page
Add inside html head <head> </head> the jQuery js file
Method 1: Use CDN hosted js file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Method 2: Download jquery.min.js then
<script src="/path/in/your/server/jquery.min.js"></script>
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Good evening everyone. I know this will seem like an extremely easy subject for many here, but I've been struggling for a while to reconstruct a function I have in order to make it dynamic and reusable site-wide.
The main struggle I'm having is returning an Array using the following:
var arr = getData("admin/fullDatabaseAccess.php");
This doesn't return the array as expected. Now, without writing every possible variation of what I did to the getData function in an attempt to return the array which it creates, I'll first show you the original function which works:
function getData() {
var xmlhttp = new XMLHttpRequest();
var url = "admin/fullDatabaseAccess.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
processResponse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
var arr = JSON.parse(response);
// do stuff with the array - I originally modified the DOM using jQuery here, however I now want to use this entire getData function as a more generically useful function
}
}
I would then trigger the getData function on the single page which I was using this code with to generate an array, followed by modifying the page elements with the array data.
THIS BRINGS ME TO MY PROBLEM - I tried to make this function re-usable across the site by creating this version below, and calling the array data using the code line I posted at first (var arr = ..):
function getData(file) {
var xmlhttp = new XMLHttpRequest();
var url = file;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
processResponse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
var arr = JSON.parse(response);
return arr;
}
}
I cannot seem to feed the data back to the variable. I've tried restructuring the function quite a lot to return values within the nests etc but I've got to the point where I'm confusing myself and can't really show the examples I tried as I deleted them and decided to start again.
Any help would be greatly appreciated!!
You need to provide a callback to getData, like this
function getData(file, cb) {
var xmlhttp = new XMLHttpRequest();
var url = file;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Calls the callback function with the response data
cb(processResponse(xmlhttp.responseText));
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
var arr = JSON.parse(response);
return arr;
}
}
getData(file, function(data) {
// data is now what's being returned from processResponse()
});
I'm using XMLHttpRequest to read a text file (on local) after a period of time (after 10s).
After 10s, XMLHttpRequest retrieves the text file but the content (responseText) does not changed even though I have changed it.
Here is my code:
var list = [];
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText.length == 0) {
undef();
}
else {
def();
}
}
}
getFile();
function getFile() {
list = [];
xhr.open("GET", chrome.extension.getURL('text/list.txt'), true);
xhr.send(null);
}
var myVar = setInterval(function(){getFile()}, 10 * 1000);
function def() {
// do something
}
function undef() {
// do something
}
I don' know why and how to fix it, please help.
The fast/lazy solution is to change your link address without changing the file it's accessing.
Modify your link with LinkToFile+"?="+Math.random()
It won't match anything in the cache but it will fetch the same file.
I found the problem, it is that the folder containing the file that I use when coding is different from the folder containing the extension when added to Chrome.
I just modified the wrong file.
Thank you everyone for your help.
I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.
UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:
var materialFilename;
function loadOBJModel(filename)
{
// ...
var req = new XMLHttpRequest();
req.open('GET', filename);
req.responseType = 'text';
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line)
{
readLine(line);
});
}
}
req.send();
alert(materialFilename);
// ...
}
function readLine(line)
{
// ...
else if (tokens[0] == "mtllib")
{
materialFilename = tokens[1];
}
// ...
}
You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.
To scan line-by-line, you can use split(). E.g. Something like this ...
var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line, i) {
// 'line' is a line of your file, 'i' is the line number (starting at 0)
});
} else {
// (something went wrong with the request)
}
}
}
req.send();
If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.
You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.
Once you have the data, parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for that out of the box.