JavaScript: Variables not working outside function? - javascript

Why cannot I call variables that I have defined inside a function? This is my code...
var username;
var rank;
var steamid;
var avatar;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "null") {
} else {
var infoArr = JSON.parse(this.responseText);
var username = infoArr.username;
var rank = infoArr.rank;
var steamid = infoArr.steamid;
var avatar = infoArr.avatar;
testIt();
}
}
};
xhr.open("GET", "../getInfo.php", true);
xhr.send();
function testIt() {
alert(username);
}
Function testIt() is returning: undefined
What my code does is to get info from a JSON encoded page and make variables.

If you want to use the variables outside of the function, they need to be defined outside of the function.
var username, rank, steamid, avatar, infoArr, username, rank, steamid, avatar;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "null") {
} else {
infoArr = JSON.parse(this.responseText);
username = infoArr.username;
rank = infoArr.rank;
steamid = infoArr.steamid;
avatar = infoArr.avatar;
testIt();
}
}
};
xhr.open("GET", "../getInfo.php", true);
xhr.send();
function testIt() {
alert(username);
}

Related

API not responding

The app that I'm working on does not respond with the API address. I only get the ajax responding, but not the weather api that I'm trying to call.
I've tried everything that I could think of with my current knowledge.
let search = document.getElementById("search-bar");
let temp = document.getElementById("temperature");
let input = document.getElementById("input");
let city = document.getElementById("city");
const key = "";
input.addEventListener("keyup", enter);
function enter(event) {
if (event.key==="Enter") {
details();
}
}
function details() {
if (searchInput.value === ""){
} else {
let searchLink = "https://api.openweathermap.org/data/2.5/weather?q={}" + searchInput.value + "&appid=" + key;
httpRequestAsync(searchLink, talk)
}
}
function talk(talking){
let jsonObject = JSON.parse(talking);
city.innerHTML = jsonOject.name;
temp.innerHTML = parseInt(parseInt(jsonObject.main.temp - 273) + "°");
}
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
request.open("GET", url, true); // true for asynchronous
request.send();
}
The expected outcome should be the weather api being called and displayed information in the console.
Try replacing last function with this:
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
httpRequest.open("GET", url, true); // true for asynchronous
httpRequest.send();
}
I just corrected variable naming

How to use variable from one method in another?

How to use site variable value from onreadystatechange method in soap method?
My code:
soap(value) {
var siteValue = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'URL', true);
var to_json = require('xmljson').to_json;
var sr = xyz
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
soapres = xmlhttp.responseText;
this.soapresponse(soapres);
to_json(soapres, function(error, data) {
var a = data['soapenv:Envelope']['soapenv:Body']['wss:readResponse']['readReturn']['resultXml']['_'];
var jsonR = JSON.parse(a);
var sitee = jsonR.SALFCY; //site
siteValue = JSON.stringify(sitee);
alert(siteValue);
});
}
}
}
}

Return value to use outside XMLHttpRequest's scope

I am doing a XMLHttpRequest which is in it's own function. I want to return the price1 var to be used by other functions. But it seems to be lost in the scope. Code below -
var dataControl = (function () {
var getPrice = function(sym){
var xhttp = new XMLHttpRequest();
var response, price1;
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response = JSON.parse(this.responseText);
price1 = response['Data'];
price1 = price1[0].open;
console.log(price1);
return price1;
}
};
xhttp.open("GET", "https://min-api.cryptocompare.com/data/histominute?fsym=XRP&tsym=USD&limit=60&aggregate=3&e=CCCAGG", true);
xhttp.send();
}
return {
getItem: function () {
getPrice();
}
}
})();
You can use the Callback Paradigm to get the data that you need
var dataControl = (function () {
var getPrice = function (cb) {
cb = (typeof cb === 'function' && cb) || function(){};
var xhttp = new XMLHttpRequest();
var response, price1;
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response = JSON.parse(this.responseText);
price1 = response['Data'];
price1 = price1[0].open;
console.log(price1);
// Assuming error first callback paradign
cb(null, price1);
}
};
xhttp.open("GET", "https://min-api.cryptocompare.com/data/histominute?fsym=XRP&tsym=USD&limit=60&aggregate=3&e=CCCAGG", true);
xhttp.send();
}
return {
getItem: function (cb) {
getPrice(cb);
}
}
})();
dataControl.getItem(function(err, data){
if(err){
// Handle error
return;
}
console.log(data); // Value of price1
});

AJAX does not return object

I am using AJAX GET to get a local JSON file and it does that, but once i try to return it says undefined.
ScoreHandler = function () {
this.getScores = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};
HighScores = function (scoreHandler) {
var scoreHandler = scoreHandler;
var scores = this.scoreHandler.getScores();
//This logs undefined
console.log(scores);
}
Just implement a callback for response, something like this
ScoreHandler = function () {
this.getScores = function(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
if(typeof callback === 'function')
callback(data);
//return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};
HighScores = function (scoreHandler) {
var scoreHandler = scoreHandler; //why this line use it directly
var scores = this.scoreHandler.getScores(function(data){
console.log("response", data); //you can see the data here
});
//This logs undefined
console.log(scores);
}

Return value from AJAX onreadystatechange Event

I have some problems with returning a value from a function into a variable. It is apparently "undefined". This apparently happens due to the asynchronity of JavaScript. But in my case I don't know how to circumvent it with "callbacks" or "promises". Please see code below. I would like to return the exchange rate saved in "value" back to "rate" and use it further in my code. Any ideas?
var rate = rateCalc();
var currency = "EUR";
function rateCalc(){
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
alert("At this position the value is defined: "+ value);
return value;
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else {
value = 1;
return value;
}
}
alert("The return statement somehow didn't work: "+ rate);
I'm a newbie, by the way. So sorry, if this question has already been asked like a million times before.
Thanks
René
You can't return anything from a async function in JS. So create a new function and use it as a callback function. See the below example.
var rate = rateCalc();
var currency = "EUR";
function rateCalc(){
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
alert("At this position the value is defined: "+ value);
valueCallBack(value); //Callback function
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else {
value = 1;
return value;
}
}
function valueCallBack(value){
console.log("value is " + value);
}
Update : You can use the Promise API introduced in the ES6 or use JQUERY deferred objects.
xmlhttp.send() shouldn't be empty. Try this. I hope it will do the job!
xmlhttp.send(null);
You can send the response value to another function so when you have a value it will be displayed without it being undefined.
Try this:
rateCalc();
var currency = "EUR";
function rateCalc() {
var value;
if (currency != "EUR") {
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
show(value);
}
};
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
} else {
value = 1;
show(value);
}
}
function show(rate) {
alert("Value: "+ rate);
}
So this is how I changed the code now. The call back function is used for all further calculations with the called back value. Thanks again to #Jijo John and #nx0side.
var currency = "HKD";
var value;
if (currency != "EUR")
{
var xmlhttp = new XMLHttpRequest();
var rateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D"+"EUR"+"HKD"+"%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
value = json.query.results.row.rate;
valueCallBack(value); //Callback function
}
}
xmlhttp.open("GET", rateURL, true);
xmlhttp.send();
}
else
{
valueCallBack(1);
}
//in this function all further calculations with "value" need to take place.
function valueCallBack(value)
{
//example
var result = 70000/value;
console.log("Result is " + result);
}

Categories

Resources