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 years ago.
I'm not new to js but there's a stupid problem with jquery get method that it can't change global variable and I don't know why?
function getData(data) {
re=null;
$.get("http://example.com/api.php",{ d:data}).done(function(result){
re = true;
}).fail(function(){
re = false;
});
console.log(re);
return re;
}
If you see the console it's still null !
Any ideas?
UPDATE :
My problem is not with console.log() , actually the problem is that I cant store and return value like this :
alert(getData(data));
This still returns null.
This is because $.get is an asynchronous call and by the time re variable is reassigned a new value, console.log is getting executed.
You can use a callback function when calling your async function getData(data).
function getData(data,callback) {
$.get("http://example.com/api.php",{ d:data}).done(function(result){
callback(true)
}).fail(function(){
callback(false);
});
}
//call it with your data and callback function
getData(data, function(response){
console.log(response); // this will contain true or false as returned from your getData function.
})
I hope this helps.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I'm scraping some data from a webpage using JQuery, but when I try to set the value to a local variable, it becomes undefined. I've searched everywhere on the scope of $.get() method as well as other instances where a variable is undefined when returned but not when printed to the console and I've hit a dead end. Is there something I'm missing? Why can't I point to the variable inside $.get()?
function scrape(url) {
let imageUrl = "";
$.get(url, function(response) {
imageUrl = response.toString().split("<meta property=\"og:image\" content=")[1].split("\"")[1];
console.log(imageUrl); // THIS PART WORKS AND PRINTS DESIRED URL
});
console.log(imageUrl); // this prints nothing...
return imageUrl; // returns undefined...
}
scrape("https://www.instagram.com/p/BfKjQxcgv-E/");
$.get is asynchronous. Thus are you returning the blank imageUrl before the $.get method has returned its response.
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
To debug this and see how it works you could try:
function scrape(url) {
let imageUrl = "";
$.get(url, function(response) {
imageUrl = response.toString().split("<meta property=\"og:image\" content=")[1].split("\"")[1];
console.log(imageUrl); // THIS PART WORKS AND PRINTS DESIRED URL
console.log('Running secondly');
});
console.log('Running first');
console.log(imageUrl); // this prints nothing...
return imageUrl; // returns undefined...
}
The solution:
Either use $.ajax and configure it like you want, with async set to false. Or you can globally change the ajax setup for jQuery using:
jQuery.ajaxSetup({async:false});
The ajax call you are doing is async. And the console.log is printed after the response from the $.get(url) is received. the function $.get itself is finished before that.
So imageUrl is still empty directly after the $.get has finished
in the function that is part of the $.get you should handle the imageUrl. If you want to change an image in your html you should do it there. You cannot just return the url if you are using async.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm doing a GET request with jQuery inside of a function and trying to set a variable declared earlier in that function with the result. However, it comes up as undefined. Am I missing the concept here? How can I make something like this work? Thanks.
function doSomething1() {
var x;
$.get( window.location.href, { q: 'stuff', q2: $('input').val() }, function(data){
// value shows up
console.log(data);
x = data;
});
return x;
}
function doSomething2() {
// comes up as undefined.
console.log(doSomething1());
}
doSomething2();
This is a fault of the asynchronous effect of $.get() requests. You are returning x before the get has a chance to do anything. It takes a while to wrap your head around async functions.
The order of events is as follows:
doSomething2() calls doSomething1()
doSomething1() defines x without a value begins the GET request, and returns undefined.
doSomething2() logs the returned x value
The GET request finishes and processes its success function
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I try do this :
<script>
FB.getLoginStatus(function(response) {
if (response.status==='connected') {
var fb_status="on";
} else {
var fb_status="off";
}
});
alert("ok"+fb_status);
</script>
If i put alert inside function , this alert works , by other side , if i put this alert outside , no works
i supose this it´s more or less the same as global vars in php but no have many experience in Javascript
I only need the same i put in the example for detect in a var the result from function but as in the case i put as example , outside function , i try many things but no get results
Regards and thank´s for the help to community
FB.getLoginStatus is async function so when you try getting fb_status outside it, you get undefined because FB.getLoginStatus didn't return any result yet
As the FB.getLoginStatus call is asynchronous, the result only occurs later and is only relevant inside the event handler:
e.g.
<script>
FB.getLoginStatus(function(response)
{
// This line gets called many millisconds later
console.log("When I have a status");
if (response.status==='connected')
{
var fb_status="on";
}
else
{
var fb_status="off";
}
alert("ok"+fb_status);
});
// This line executes long before the callback returns
console.log("After call");
</script>
Check out the console to see the order of events:
"After call"
"When I have a status"
You mention in comments you want to use the value elsewhere. The problem will be the timing as the result you want will only occur later.
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 8 years ago.
This is more of a basic JQuery/Javascript question: How do I get data out of the getJSON function?
The following code works great until the function ends. I have several getJSON that will need to run one-after-the-other and I would like to avoid nesting them if I can:
//Using the Web API to pull all the information out for the current ORG ID
$.getJSON('http://localhost:8081/dhis/api/organisationUnits/' + vuCurrentFacilityID + '.json', function (data) {
//alert(data.message);
console.log(data);
vuCurrentFacilityName = data.name;
vuParentFacilityID = data.parent.name;
});
alert(vuCurrentFacilityName); //does not work
What Gotcha* am I missing?
This question is very similar to the following.
if you call $.getJSON() you are entering an asynchronous context, and everything after it gets executed immediately. So your alert is called before the server responds.
use deferreds instead
var promise = $.getJSON( ... );
promise.done(function() {
alert("yeah");
});
This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
In the following code the alert inside the function works fine, but the second has variable undefined, and yet I have delcared the variable outside of the function. Why is this?
var data = [];
$.post(
'matchEngine.php',
function(data) {
for (var i = 0, len= data.length;i <len; i++) {
for ( h = 0, len2= data[i].length;h <len2; h++) {
data[i][h][0]=(data[i][h][0])*30;
data[i][h][1]=(data[i][h][1])*30;
data[i][h][3]=data[i][h][3].replace(/\"/,"");
}
}
alert(data[0][0][0]);
}
);
alert(data[0][0][0]);
if you are suffering a similar problem the following How to return the response from an AJAX call? has the definitive explanation and answer.
The reference data in the function parameter and outside the function are different variables. In first case, it is in global scope, and in the second it in the local scope..They are completely different.
The example illustrates the issue....
var data=2;//this
function fun(data){ //and this are different
alert(data);
}
var data2=3;
fun(data2);
You can try this:
var data = [];
var myRequest = $.post(
/* your stuff */
);
myRequest.done(function() { alert(data[0][0][0]); })
As pinkpanther noted, the local data variable inside your $.post callback is not the same variable as the data variable outside the function.
Additionally, since $.post is asynchronous, you need to either pass it a callback or use the deferred object that it returns to access the response.
$.post('matchEngine.php').then(function(data){alert(data)})
for example, if you want to be able to pass the response around to other functions, you can do something like:
function doPost(url){
return $.post(url);
}
function processResponse(response) {
alert(response);
}
responsePromise = doPost("matchEngine.php");
responsePromise.then(processResponse);
As an aside, I recommend using $.ajax instead of $.post if you are going to use the callback style instead of promises. The reason being that $.ajax provides an error callback while $.post does not.