assign variable to ajax responseText [duplicate] - javascript

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

Related

Using a json value as a global variable in a script outside of a function [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 months ago.
I can't find a way to use the value obtained from the JSON function from ipify.org.
I need to use this value in another function, not just write it in HTML like in the examples on ipify.org.
I'm trying to assign a value to the window variable, but it can also be done in another way. I am trying to use the "javascript" example on the site: https://www.ipify.org/
<script type="text/javascript">
function getIP(json) {
window.ipa = json.ip;
}
alert(window.ipa); //return "undefined"
</script>
<script type="text/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
You have to make the request to and capture the response from api.ipify.org in your script, there are many ways to do this, I used the old, native XMLHttpRequest API.
You also need to attach this function call to an event (I used "onload" bellow).
Example:
function xhrget(items, route, callback){
const xhr = new XMLHttpRequest();
xhr.open('GET', route);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.timeout = 1000;
xhr.send(encodeURI(items));
xhr.ontimeout = function(e){
callback('404');
};
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
if(xhr.status >= 500 && xhr.status < 600){
callback('An error occurred, please wait a bit and try again.');
}
if(xhr.status === 404) {
callback('404');
}
};
}
function getIP() {
xhrget(null, "https://api.ipify.org", (ip) => {
console.log(ip);
window.ipa = ip;
alert(window.ipa); //return "undefined"
});
}
window.addEventListener('load', (event) => {
getIP();
});

Best method to save an XMLHttpRequest() to variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
What is the best method to save a XMLHttpRequest to a variable to use in a if statement. I'm trying to get the image size and depending on the size do something.
** *Please note that I'm using a random image from the internet for this question. I'm currently testing using a local server * **
This is what I have tried so far:
function get_image_size(imgurl) {
var xhr = new XMLHttpRequest();
let x
xhr.open('HEAD', imgurl, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
x = xhr.getResponseHeader('Content-Length');
console.log(xhr.getResponseHeader('Content-Length')) // This works! returns bytes
} else {
console.log('ERROR');
}
}
};
xhr.send(null);
console.log(x) // This doesn't work
return x // This doesnt return anything
}
let image_size = get_image_size("https://images.ctfassets.net/hrltx12pl8hq/7yQR5uJhwEkRfjwMFJ7bUK/dc52a0913e8ff8b5c276177890eb0129/offset_comp_772626-opt.jpg?fit=fill&w=800&h=300")
// image_size returns "undifined"
I've also tried:
function get_filesize(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url, true);
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(parseInt(xhr.getResponseHeader("Content-Length")));
}
};
xhr.send();
}
get_filesize("https://images.ctfassets.net/hrltx12pl8hq/7yQR5uJhwEkRfjwMFJ7bUK/dc52a0913e8ff8b5c276177890eb0129/offset_comp_772626-opt.jpg?fit=fill&w=800&h=300", function(size){image_size = size})
But still no luck.
You're making an asynchronous request, therefore, you can't have the value you need immediately assigned to x for use, your code needs a way to await the request before you can use or return x;
One approach is to wrap your get_image_size function in a Promise like this
function get_image_size(imgurl) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', imgurl, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(xhr.getResponseHeader('Content-Length'))
} else {
console.log('ERROR');
}
}
};
xhr.send(null);
})
}
and use it like this
const IMAGE_URL = "https://images.ctfassets.net/hrltx12pl8hq/7yQR5uJhwEkRfjwMFJ7bUK/dc52a0913e8ff8b5c276177890eb0129/offset_comp_772626-opt.jpg?fit=fill&w=800&h=300";
get_image_size(IMAGE_URL).then((size) => {
console.log(size)
// YOU CAN ONLY USE SIZE HERE.
// NOT OUTSIDE OR REASSIGNED
// COS IT MAY NOT BE AVAILABLE AS THIS IS AN ASYNCHRONOUS OPERATION
})
You can only use the value of size inside the callback of the chained .then() method.
It will NOT work if you reassign or try to access it from outside, as it may not be available at the time your code executes.
Another approach is to use the callback function, which I see you have tried, but the problem is that you were reassigning it like this image_size = size.
You can only use it within that callback function.
So technically you need to wrap all the code that needs the image-size inside that callback.

Making Chrome Extension, can't assign global variable properly in js-file (single file) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
Strange error, says config is undefined, but that is false:
There is no misspellings:
I am not JavaScript programmer, and that is my first extension. I hope it is a known issue. The only thing used is AJAX. The code starts like this:
var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
config = JSON.parse(this.response);
}
}
req.open("GET", chrome.extension.getURL('/config.json'), true);
req.send();
// here console.log(config) will return undefined.
In other words variable is assigned strangely.
Since XMLHTTPRequests are asynchronous (they don't happen instantly as the code flows) you'll have to either put the code inside their load event listener, or call a function that will have that code in it from the same event listener:
var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
config = JSON.parse(this.response);
// any code that uses config should be here
}
}
or:
var config;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
config = JSON.parse(this.response);
// call doMagicStuff here
doMagicStuff();
}
}
function doMagicStuff() {
// code that use config goes here
}
in the latter, you might as well just pass config as parameter to doMagicStuff.

Unique function for ajax request not working [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'd like to create unique function for ajax post request.
This is actual source code:
function doAjax(url, postData) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
return xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(postData);
}
console.log( doAjax('shipment.php', 'fname=test1&lname=test2') );
But it's not working, the console shows "undefined".
But, if I change return on alert() - everything is OK.
So, why return now working ?
Your function doAjax does not actually return something. When you do xhttp.onreadystatechange = function() {...}; you just set a callback for an event that means this function isn't triggered immediately. No matter what you want to do, you will have to do (or trigger) it inside your callback.

How to return to the function calling the current function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
How to return to the calling function (the function above). I would like to return true if the file exists when doing UrlExists('file.png') :
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, true);
http.onerror = function(e){
//console.log('......onerror: ' + JSON.stringify(e));
if (typeof e !== 'undefined'){
return false
}
};
http.send();
return http.onerror();
}
Use XMLHttpResponse as async. Because async responses may not be received in the order that they are requested and since you may be checking for multiple files it may be a good idea to check the responseURL property before acting on the case where the file does not "exist" (is not found or returns error, etc.)
jsFiddle example: http://jsfiddle.net/5f42L6nz/4/
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
function UrlExists(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true); // true => async request
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// URL found, do stuff for "exists"
alert("url exists:\r\n" + xhr.responseURL);
} else {
// URL not found, could check xhr.status === 404, etc.
// do stuff when URL not found, but no exception/error thrown
alert("not found or unexpected response:\r\n" + xhr.responseURL);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
}
var url = '/'; // just an example, get web app root
UrlExists(url);
UrlExists("/badurl");

Categories

Resources