Why the variable value from is not accessible in following code snippet? - javascript

I've following Javascript code snippet :
authData=ref.getAuth();
if(authData == null){
//TODO find an elegant way to manage authorization
// window.location = "../index.html";
} else {
ref.child("users").child(authData.uid).on("value", function(snapshot){
$( "span.user-name").html(snapshot.val().displayName);
loggedInUser.displayName = snapshot.val().displayName;
//alert("Name inside : "+loggedInUser.displayName);
//Here it displays the value
});
}
alert("Nameada is out : "+loggedInUser.displayName);
//Here it shows 'undefined'
why?
I want to use the variable value loggedInUser.displayName where did I shown alert.
Can someone please help me in accessing the value and displaying the alert?
Thanks.

Your final alert is executed when the callback function (function(snapshot){ ... }) has not yet been called. Note that the callback function is called asynchronously, so it only gets executed after the currently running code has completed and the value event is triggered.
This also explains why the inner (commented out) alert does work. Just realise that this piece of code (the call back function) is executed later than the other alert, even though it occurs earlier in your code.
You could "solve" it by calling another function from within the call back, like this:
authData=ref.getAuth();
if(authData == null){
//TODO find an elegant way to manage authorization
// window.location = "../index.html";
} else {
ref.child("users").child(authData.uid).on("value", function(snapshot){
$( "span.user-name").html(snapshot.val().displayName);
loggedInUser.displayName = snapshot.val().displayName;
whenUserLogged();
});
}
function whenUserLogged() {
alert("Name : "+loggedInUser.displayName);
// anything else you want to do....
}
Some suggestions for improvement
Don't use too many global variables (in your code all of them are global), and instead pass variables as function arguments.
You may want to look into promises.

Related

javascript can't assign variable values due to asynchronous function.

In my JavaScript code below, I cannot get user_likes to take the value of response. I can Console output "response", and it has the values I need. However, when I try to Console output user_likes, I get undefined. What gives?
function fqlUserLikes(user_id) {
var user_likes;
FB.api(
{
method: 'fql.query',
query: 'SELECT page_id,name,type FROM page WHERE page_id IN (SELECT page_id FROM page_fan WHERE uid=' + user_id + ')'
},
function(response) {
user_likes=response;
}
);
Console.log(user_likes);
return user_likes;
}
Thanks for any help,
I.N.
Your method is asynchronous, so when you try to log and return the variable, it hasn't actually been assigned yet. Take the below snippet:
//Do what you need to do in here!
function(response) {
user_likes=response;
});
//The below code is executed before the callback above.
//Also, it should be console, and not Console. JS is case sensi.
Console.log(user_likes);
return user_likes;
Your function that changes the value of user_likes is not called immediately. FB.api() starts the process of calling the API, and then returns. Your console.log() call happens at this point, and then your function returns the user_likes value to its caller. Then, at some later point, the api call completes, your callback function is called, and it sets user_likes to the appropriate value. Unfortunately, there's nothing left to read that value.
You need to completely restructure your code to make it work. Javascript doesn't really support waiting for things to happen in the middle of code; it's a very asynchronous language. The best way is if you pass a callback function that actually uses the new value, rather than trying to store it in a variable for something else to read.

Javascript Variable Not Changed Outside of Function Scope

I have the following function:
function loginStudent() {
var advisorKEY = "<dtml-var expr="py_get_alias()">";
var studentKEY = "<dtml-var SID>";
var URL = "py_logging_sessionOpen?AdvisorKEY=" + advisorKEY + "&StudentKEY=" + studentKEY;
key = "";
$j.get(URL, function(data) {
key = data;
});
alert(key);
}
The py_loggin_sessionOpen is just a python script running on my server.
It returns a single string. I need the response of that script to determine the next action. The script returns the value perfectly, and I can easily check the value by putting an alert within the function(data) in get.
My main question is: how to get the key value to be changed outside the scope of function(data)?
I assumed because I defined it externally it would act as a global variable.
Moving it outside loginStudent() does not solve the problem either.
Any ideas?
$j.get() is going to be an asynchronous call. That means it fires, and the rest of the execution continues. Anything that relies on that call needs to be done in the callback, like so:
$j.get(URL, function(data) {
key = data;
alert(key);
} );
If everything else is good, you'll see the value you expect.
The problem with your code is that $j.get executes asynchronously. That's the reason you pass a callback to it.
If you wish to write asynchronous code synchronously then you should read this answer: https://stackoverflow.com/a/14809354/783743
Edit: It seems that you have created a global variable called key by not declaring it with var. Hence it should be visible in other functions as long as they are called after the callback.
Would you care to provide us these other functions?

JavaScript variable scope

Here's my code
errors=0;
$(document).ready(function () {
var chk=$("#usnm").val();
$.post("register.php",{'chkuser':chk},function(data){
if(data==" Username already exists.Choose a new one"){
errors++;
alert(errors);
$("#alerts").html(data);
}
});
if(errors==0){
alert(errors+"post");
}
});
Here, the first alert gives me a "1" whereas the second alert runs, so therefore it give me '0post' . What i'd like to know is: How is the value of the variable errors, changing to 0 all of a sudden after being 1 ?
Thanks
Change errors=0; to var errors=0;
and put the error check inside the $.post function:
$.post("register.php",{'chkuser':chk},function(data){
if(data==" Username already exists.Choose a new one"){
errors++;
alert(errors);
$("#alerts").html(data);
}
if(errors==0){
alert(errors+"post");
}
});
jquery.post is called asynchronously. you might be debugging it locally otherwise the second alert would go on the first place. anyways because it runs async the value is different inside and outside the post function

variable scoping in javascript

My code is as follows:
jQuery(document).ready(function() {
var pic = 0;
FB.init({appId: '1355701231239404', status: true, cookie: true, xfbml: true});
FB.getLoginStatus(function(response) {
if (response.session) {
pic = "http://graph.facebook.com/" + response.session.uid + "/picture";
alert(pic);
} else {
window.location = "index.php"
}
});
});
</script>
The issue is that the pic inside my if statement has a different scope with the one I declared above? Why and how do I make them the same?
What I want is to use this var pic (the one that has been assigned by the if statement) inside the body of my html. I will have another script inside the body, a document.write that uses this pic variable.. as of now when I do a document.write it always gives me 0, as if it's not assigned inside the if statement
The issue is that the pic inside my if statement has a different scope
No, it isn't. JavaScript scope is by function. var pic = 0; scopes pic to the anonymous function passed to ready(). The anonymous function passed to getLoginStatus() doesn't use var at all, so the scope of pic there is the same.
(Since you didn't say what outcome you got or what outcome you were expecting, it is hard to say what the solution to your problem actually is)
But there is only one pic in that snippet. So the issue you describe doesn't exist. What problem are you experiencing? How does the code misbehave compared with what you expect?
Update
Okay, your actual problem is that you're expecting pic to be updated so you can use the value of it elsewhere. But consider:
FB.getLoginStatus(function(response) { ... });
The reason that function executes a callback, instead of returning response as a return value, is because it is asynchronous. It make take a while to get the response, and so it doesn't execute the callback immediately. So your other piece of code is probably executing before that happens, i.e. before pic has been properly initialised with a value.

javascript parsing

i have this block of code:
$(document).ready(function() {
//<![CDATA[
var who;
FB_RequireFeatures(["Api"], function(){
var who = api.get_session().uid;
alert(who);
});
alert("the uid is: "+who);
//]]>
});
the problem:
the code outside the FB_RequireFeatures block is executing before the one inside it.
due to which the value of who is coming out to be undefined.
what am i doing wrong?
The FB_RequireFeatures function appears to be making an asynchronous call, so you're not doing anything wrong, that's just the way it works - the alert is called before the request comes back.
You must design your code in a way that the code that depends on the result of the FB_RequireFeatures functions are called only after the request completes. You can call another function inside the callback, for example:
var who;
$(document).ready(function() {
FB_RequireFeatures(["Api"], function() {
who = api.get_session().uid;
doSomeOtherStuff();
});
});
function doSomeOtherStuff() {
alert("the uid is: " + who);
}
Now the doSomeOtherStuff function is called only after the FB_RequireFeatures function finishes, and you should do all following code inside the doSomeOtherStuff function – which you can name to be anything you want, obviously.
I moved the who variable out of the ready block to keep it in scope for the doSomeOtherStuff function, and removed the var from the inner function so that you're referencing the original variable instead of creating a new one, otherwise it's the same.
You're making a new local who variable. Remove the var from the place where you set who. Also, you can't reference who until the callback to the FB_RequireFeatures function is run.

Categories