AJAX response does not get assigned to variable [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 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);
});

Related

Why is my callback returning an undefined value? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to get a value from a callback, but it returns an undefined value.
Below is the code I'm using:
function getJSON(url, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (callback) return callback(this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function getUserName() {
getJSON("this is my url", function(resultJSON) {
return JSON.parse(resultJSON).user[0].displayName;
});
}
var userN = getUserName();
document.getElementById("username").innerHTML = "Hi " + userN;
I know this has been asked a billion times but I can't get it working the way I need with previous answers. The html element is still giving a "Hi undefined".
Any thought or suggestion?
function getJSON(url, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (callback) return callback(this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function getUserName() {
getJSON("https://my-json-server.typicode.com/typicode/demo/profile", function(resultJSON) {
const userN = JSON.parse(resultJSON).name;
document.getElementById("username").innerHTML = "Hi " + userN;
});
}
getUserName();
<div id="username">Greetings</div>
You should write code for Hi + <userN> inside of 2nd parameter(callback function) of getJSON.

Can't get JSON file into variable

I am trying to parse the content of the JSON file into a variable called weatherArray. However, this variable is always an empty array.
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
/* Expecting the value to be stored and be shown in console*/
console.log(weatherArray);
You're checking the results before they come back. You need to move the line:
console.log(weatherArray);
To inside the onreadystatechange function, which will check the results once they arrive. Also you need to call the loadDoc() function (you probably did that).
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
console.log(weatherArray);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
loadDoc();
EDIT If you like to process the results in another function instead of inside onreadystatechange, you can call that function from onreadystatechange. You can do that with your global weatherArray, but I just recommend in this case to simply pass the data in a parameter:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
showWeather(JSON.parse(this.responseText));
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
function showWeather(weatherArray) {
console.log(weatherArray);
}
loadDoc();
Ajax is asynchronous call, and you are printing data before invoking the ajax call,
I made some changes try it.
let weatherArray = [];
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
weatherArray = JSON.parse(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true);
xhttp.send();
}
loadDoc();
/* Expecting the value to be stored and be shown in console*/
I'd like to provide an alternative modern approach using the Fetch api and Promises.
First fetch from the api
Convert it to json
Return the promise
Listen for the promise and log the result in the callback
function loadDoc() {
return fetch("https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12")
.then(res => res.json())
}
loadDoc().then((weatherArray) => {
console.log(weatherArray);
})

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.

Function returns undefined in Javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Can not figure it out how to return value (string) from this function:
function loadPage(url) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//var html = xhttp.responseText
var html = document.documentElement.outerHTML;
return html
}
}
}
console.log(loadPage("http://stops.lt/vilnius/#trol/2/a-b"))
When I use console.log(html) inside xhttp.onreadystatechange it prints correct results, but I don't understand how to return loadPage(url). Tried both return xhttp.onreadystatechange and return xhttp.onreadystatechange() and none of these works.
Fuction loadPage is async, you need to use callback function(or Promise):
function loadPage(url, cb) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//var html = xhttp.responseText
var html = document.documentElement.outerHTML;
cb(html);
}
}
}
loadPage("http://stops.lt/vilnius/#trol/2/a-b", function(html){
console.log(html);
});

Categories

Resources