Function returns undefined in Javascript [duplicate] - javascript

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);
});

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.

AJAX response does not get assigned to variable [duplicate]

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);
});

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);
})

How can I keep 'this' in scope through callbacks and anonymous functions? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I'm trying to load some JSON into a JavaScript class and assign some properties from the JSON to properties on an instance of the class, but I'm having trouble with 'this' and scope. I'm pretty sure the solution involves arrow functions, but I can't figure out how to piece things together.
Here's what I have so far:
class Test {
constructor(url) {
this.loadJSON(url, this.init);
}
loadJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.response);
}
};
xhr.send(null);
}
init(response) {
console.log(response.description);
// this is undefined
this.description = response.description;
}
}
In the init() method, the console.log works as I'd expect, but I'm having trouble assigning anything to the object - I just keep getting 'this is undefined.'
Either modify your callback(xhr.response); code like below :
callback.call(this, xhr.response);
Or, modify this.loadJsON code like below :
this.loadJSON(url, this.init.bind(this));
Here is the full solution :
class Test {
constructor(url) {
this.that = this;
this.loadJSON(url, this.init);
//Or, this.loadJSON(url, this.init.bind(this)); In that case you dont have to modify "callback(xhr.response);" code
}
loadJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback.call(this, xhr.response);
}
};
xhr.send(null);
}
init(response) {
console.log(response.description);
this.description = response.description;
console.log(this.description);
}
}
let t = new Test('MY URL');

GET function console error

The logic:
my_function looks through file.txt, if it finds the word "Hello", returns true. If not, false.
The problem:
Uncaught type error: contents.includes is not a function
Limitations:
Can only use plain javascript
function my_function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(contents) {
if (this.readyState == 4 && this.status == 200) {
//contents variable now contains the contents of the textfile as string
//check if text file contains the word Hello
var hasString = contents.includes("Hello");
//outputs true if contained, else false
console.log(hasString);
}
};
xhttp.open("GET", "http://www.example.com/file.txt", true);
xhttp.send();
}
use this.responseText instead of that parameter contents
this.responseText is the response of your ajax
function my_function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//contents variable now contains the contents of the textfile as string
//check if text file contains the word Hello
var hasString = this.responseText.includes("Hello");
//outputs true if contained, else false
console.log(hasString);
}
};
xhttp.open("GET", "http://www.example.com/file.txt", true);
xhttp.send();
}

Categories

Resources