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.
Related
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();
});
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.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
i use this javascript code for a API request to get a JSON.
function loadJSON(url) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType('application/json');
xobj.open('GET', url, false);
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
returnval = JSON.parse(xobj.responseText);
}
};
xobj.send(null);
return returnval;
}
The code is in a mouse-click event. The full URL is generated with data from the mouse click. The code is only work with sync. I have tested the code with async, but with this the code don't work.
xobj.open('GET', file, true, null, null);
With sync, the console write:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
OK, hey! There a many Threads with this question, but i don't found a solution. I use pure JavaScript, no Ajax, no JQuery.
You almost have it written asynchronously. Pass in a callback function to get your returnval.
function loadJSON(url, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType('application/json');
xobj.open('GET', url);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == '200') {
returnval = JSON.parse(xobj.responseText);
callback(returnval);
}
};
xobj.send(null);
}
loadJSON('https://jsonplaceholder.typicode.com/users', function(result) {
console.log(result)
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am using this code to get the contents of data.dat. Here are the files:
main.js
function getData() {
var result;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
result = this.responseText.split(",");
}
};
xhttp.open("POST","data.dat",true);
xhttp.send();
return result;
}
data.dat
A,B,C
However, getData() returns an empty string. When I log this.responseText this way:
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
result = this.responseText.split(",");
}
I get ["A","B","C"]. What am I doing wrong?
Since AJAX stands for Asynchronous JavaScript And XML, you're using an asynchronous call in order to get your desired output. The issue is that return result statement is returned before your AJAX call is finished and that's why you're receiving empty result.
You should use a callback function.
function getData(callback) {
var result;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
result = this.responseText.split(",");
callback(result);
}
};
xhttp.open("POST","data.dat",true);
xhttp.send();
}
getData(function(result){
console.log(result);
});
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