javascript variable scope issue undefined [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
function getData() {
var photo,
comment,
url;
$.getJSON('http://url.info/verify/settings.php', function (data) {
photo = data.photoMSG;
comment = data.commentMSG;
url = data.photoURL
});
console.log(photo); //undefined
console.log(comment); //undefined
console.log(url); //undefined
}
I'm getting undefined in console log for all of them... How to get these 3 vars visible outside of getJOSN block? I know this have been asked x100 times, I tried windiw.varName but still the same thing..

It's not a scope issue, it's an asynchronous issue. Everything inside the getJSON handler is asynchronous -- so the console.log calls will usually happen after the variables get assigned. Use an async callback instead:
$.getJSON('http://url.info/verify/settings.php', function (data) {
photo = data.photoMSG;
comment = data.commentMSG;
url = data.photoURL;
callback(photo, comment, url);
});
function(photo, comment, url) {
console.log(photo); //undefined
console.log(comment); //undefined
console.log(url); //undefined
}

Because $.getJSON is doing an ajax call, but the code after that is called before the callback within the getJSON is called. So the vars are still undefined. A typical "problem" with asynchronous behaviors.

Related

function that has an ajax events return undefined when called [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a function called 'getAuthor' and inside there's an ajax events running (refer below)
function getAuthor(id){
$.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
var author = e.name;
console.log(author);
return author;
});
}
try to run from the console, you'll see it returns "undefined" while console.log display the expected response from the ajax call.
Any, ideas help please?
Unless there is a explicit return from a function , it will always return undefined.
In console it is undefined because the function getAuthor is not returning anything. Not to be confused with the return from $.get.
The console.log statement is inside this asynchronous function. To get a return from the function getAuthor try this
function getAuthor(id){
return $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){
var author = e.name;
console.log(author);
return author;
});
}

Variable scope Javascript Module Pattern [duplicate]

This question already has answers here:
Ajax jquery async return value
(3 answers)
Closed 7 years ago.
I have the following code:
Main.User = (function(){
var currentUser = ''
var get_current_user = function get_current_user(){
Main.Mod.do_ajax('home/get_user_pnp_id','GET',function(data){
currentUser = data.username;
},null);
console.log(currentUser); //Doesn't work. It logs empty string.
return currentUser;
}
return {
get_current_user : get_current_user,
}
})();
The 3rd parameter from Main.Mod.do_ajax() is a callback success function from my ajax call. However I cannot set currentUser inside that callback function.
What seems to be the problem?
It's because your callback hasn't been called yet when the assignment is made since the callback is asynchronous. See Ajax jquery async return value and http://node-tricks.com/return-response-ajax-call/

Unable to fetch object outside of function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have the following code
function test(){
var api_url = "/Test/";
api.CFClient.load(api_url,function(success){
success.images; // Object with images
},function(error){
});
// More code to use the images returned.
I am basically unable to get the images from the success function. If i execute my code within the success function i am able to access the returned object. How do i store the returned object in a variable so i can use that object in my parent function and not the success function ?
I presume api.CFClient.load is asynchronous, and in that case you can't access success.images immediately in the test() function after invoking the load function. It will be available at some unknown time in the future, when the ajax request has completed. You'll have to invoke a different function from within your success callback and do whatever you need to do with success.images there, or else do what you need to do directly in the success callback function.
You need to account for the success function being asynchronous. You won't be able to use the returned images until the api call is complete. When it is, you can call another function and pass the images.
function test(){
var api_url = "/Test/";
api.CFClient.load(api_url,function(success){
useImages(success.images);
}, function(error){
});
function useImages(images) {
// do something with images here...
}
SO is full of errors like this(asynchronous workflow), just google for...
function test(){
var api_url = "/Test/";
function useImages(err, images) {
if (err) return console.error(err);
console.log(images);
}
api.CFClient.load(api_url,function(success){
useImages(null, success.images);
},function(error){
useImages(error);
});
}

Scope in JavaScript / jQuery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've clearly been writing too much CoffeeScript, as I am now realizing I do not have even a basic understanding of scope in pure JS.
After playing for a while, I cannot figure out the problem with the following--
$(document).ready(function() {
var myUrl = "http://notimportant.com/"
var photos = getPhotos(myUrl);
console.log(photos); //undefined
});
function getPhotos(url) {
var a;
$.get(url, function(data) {
a = data["photoset"]["photo"];
console.log(a); //my object
});
return a;
}
If I put a console.log(a) statement on the line right below 'var a = data["photoset"]["photo"];' it shows that it properly makes the GET request I'm looking for. But I'm finding it impossible to pass that object back to my main block of code, where I want to manipulate it.
Thanks in advance.
The reason photos is undefined is not because of scopes. Its because $.get is executed asynchronously. $.get() returns jqXHR object instead of an HTTP response.
onSuccess callback should be passed to getPhotos() in order to make it work correctly. Alternatively when().then() construct could be used.
$(document).ready(function() {
var myUrl = "http://example.com/";
getPhotos(myUrl, renderCatPhotos);
});
function getPhotos(url, onSuccess) {
$.get(url, onSuccess);
}
function renderCatPhotos(data) {
var a = data.photoset.photo;
console.log(a); // a is always available
}
note: you might not even need getPhotos function. You can simply $.get(url, onSuccess); in $(document).ready() instead.
Its not a matter of scope, its a matter of that you are returning an undefined variable before the $.get defines it. Consider making photos a global, then setting it in the $.get success function instead of setting it to 'a'. Inside the success function, you can then issue calls to other functions that would control displaying/processing the photos.

how can i get return value of javascript function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 8 years ago.
my code like this
var key,value;
//……some code……
function checkReg(i,j){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
alert(c.status);
return(c.status);
});
}
var temp=checkReg(key,value);
alert(temp);
The problem is when I run it in my browser, it always fist alert undefined then alert the return value; seems like that can not get the return value of function checkReg. I was so confused, what should I do?
That's because your ajax call is running asynch from the rest. Your code will already have returned before before the ajax is even triggered.
So the returning doesn't work like that, you should provide a callback to your function instead of trying to return it.
function checkReg(i,j, callback){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
alert(c.status);
callback(c.status);
});
}
checkReg(key,value, function(temp){
alert(temp);
});
you cannot do that... since ajax is ashynchronus ... by the time the success function is called and return, the alert will be called thus having temp as undefined or empty.. one way to do this is doing the thing you need to inside the success called back of getJSON... or use $.deffered or callinga calback function..
function checkReg(i,j, callback){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
callback(c.status);
});
}
checkReg(key,value, function(temp){
alert(temp);
});

Categories

Resources