This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 3 years ago.
In a function to obtain certain data with a json, I want to use this data in a variable and then use it in another function. The problem is that it does not work for me
First of all, obtaining the data with a json and printing it in place on the screen, until now, the problem starts when I save the data in a variable
function cargarPropuestas() {
var peticionLoc = new XMLHttpRequest();
peticionLoc.open('GET', 'https://api.ipdata.co/es?api-key=b3ae31a7a74386088875d7d285250b58778e13de985b2f561910b6bd');
peticionLoc.onload = function () {
var datosLoc = JSON.parse(peticionLoc.responseText);
var elementoLoc = document.createElement('div');
elementoLoc.innerHTML += (datosLoc.city + ', ' + datosLoc.country_name);
loc.appendChild(elementoLoc);
var country = datosLoc.country_name;
}
peticionLoc.send();
What interests me here is the variable COUNTRY
And here the problem begins, since when I "leave" the requestLoc.onload = function () {} I can not call the variable COUNTRY to use it below
What I need is to know how to get the information of this variable out of the function, in order to use that data
You can declare country outside both functions.
var country;
function cargarPropuestas() {
//...
peticionLoc.onload = function () {
//...
country = datosLoc.country_name;
}
peticionLoc.send();
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am new to Javascript, and Trying to write a function inside a function, but it always show undefine.
function csnotebook(){
function calculate_mw(peptide){
var total_mw=0;
var split_peptide = peptide.split("-");
// Check if the blog id is found in database
Aa.findOne({ three_letter: split_peptide[1] }, (err, aa) => {
// Check if the id is a valid ID
if (!aa) {
console.log("wrong aa");
}else{
total_mw += aa.mw;
}
return total_mw;
});
}
var publicAPI = {
mw: calculate_mw
};
return publicAPI;
}
var fred = csnotebook();
var totalmw = fred.mw("Ala-Cys");
console.log(totalmw);
I assume i can find the corresponding value mw from database, but totalmw, I always get undefined for some reson, anybody know why? Thank you!!
The inner function calculate_mw doesn't return anything, so the return value of a function is undefined unless you return something.
If you want to return the result of the Aa.findOne you should:
return Aa.findOne(...
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
How I can return a string from a javascript callback
I have two functions, main function is working on loaded.
and another function is used to calling web service.
I would like to know how can JS return the string value to main function.
thanks
function thisCallJSON(webServiceURL) {
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
gadgets.io.makeRequest(webServiceURL, function(response)
{
if(response.data && response.text)
{
var jsondata = response.data;
for (var key in jsondata)
{
var value = jsondata[key];
//alert("Member Name : "+value["memNm"]);
}
}
else
{
//alert("Member Name : Not Found !");
}
}, params);
}; function main(){
var txt_string = "";
txt_string = thisCallJSON("http://192.100.1.59");
}
You can assign the value to the variable in the scope of the main function, but it won't happen before the main function is finished executing because of the event loop. Instead, you should put your code inside the callback, or better yet, look at how you would use javascript promises to accomplish this.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 6 years ago.
I have a basic function in protractor written as :
this.getCurrentUrl = function () {
browser.getCurrentUrl().then(function(url){
console.log('url : '+url);
});
};
Now is there a way I can access the 'url' outside of the inner function scope, because I need to return this value to some other function calling this one. I need to get the value and return it from outside of then(function(url){...}
the url will be acquired async, so you can't just assign it. You probably want to hand it a callback.
function handleUrl(url) {
// here is where you do something with the url
}
// let your callback be called
this.getCurrentUrl = function(fn) {
browser.getCurrentUrl().then( function (url) {
fn(url);
})
}
// make the call with your handler
this.getCurrentUrl(handleUrl);
Another approach is to have your function return a "container" and that gets inflated later. Then later you can check your container. Since the behavior is async, you won't know when it will be ready, so you can check for it on an interval or something...
// return a container object
this.getCurrentUrl = function() {
var urlContainer = {};
browser.getCurrentUrl().then( function (url) {
urlContainer.url = url;
});
return urlContainer;
}
var urlContainer = this.getCurrentUrl(); // starts off as an empty object
urlContainer.url // undefined
// then shortly in the future
urlContainer.url // has some url
Yet a third way is to return a closure
this.getCurrentUrl = function() {
var urlValue;
browser.getCurrentUrl().then(function(url) {
urlValue = url;
});
return function() {
return urlValue;
}
}
var getUrl = this.getCurrentUrl();
getUrl(); // initially, returns undefined;
// keep trying. then shortly in the future...
getUrl(); // now has the url
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm trying to append the results from an ajax call to a paragraph using jQuery.
I would like to return the variable "myResult" from the inner getResult function and pass it to the outer buildParagraph function, but the value returned is undefined.
How do I append the value of myResults to the <p> tag as indicated below?
function buildParagraph () {
function getResult(url) {
$.getJSON(url, function(data) {
var myResult = data.results;
return myResult;
}
}
var myUrl = 'www.mywebsite.com';
getResult(myUrl);
$('<p>').html(myResult);
}
You need to have a callback function inside ajax success,Or the easiest way is move the below code to the ajax success function
$('<p>').html(data.results);
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've written a piece of javascript/jquery that reads a textfile.
I'm having trouble with the variable "fieldname". I declared it in the outer function(), and I assign a value to it in the inner function() that actually reads the file. But right after I leave the inner function, the content of the variable is lost. The code:
<script>
$(document).ready(function(){
var usedlanguage = $("#usedlanguage").html();
var fieldname = new Array();
$.get('Language.txt', function(data)
{
var lines = data.split('\n');
var res="";
for(var i = 0; i<lines.length;i++)
{
var splitup = lines[i].split('\t');
fieldname[i] = splitup[0];
res = res + fieldname[i] + '\n';
}
alert("fieldname length = " + fieldname.length); // here everything is OK
alert("" + res); //this is good.
});
alert("fieldname length = " + fieldname.length); // here it suddenly returns 0.
});
</script>
Is there something wrong with my understanding of scopes? Or is it a problem that there are two function() defined? Or something else?
You need to declare the variable outside DOM ready event to make it global. currently its context remains only in ready event and not beyond that. Use it in this way::
var fieldname = new Array();
$(document).ready(function(){
//rest code
});