Javascript Function and show global vars [duplicate] - javascript

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.

Related

How to change global variable in jquery get method? [duplicate]

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.

Javascript page not working when trying to get the ip address of the device opening the page [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am working on web ui project based on this project. Now what I want to do is that when a user opens the webpage, the ip address of the device from which this page is opened should be returned. For this I added the below code to the javascript` code here:
function myIP() {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
const ipInformation = JSON.parse(data);
console.log(ipInformation.ip);
return ipInformation.ip;
});
}
const sessionAttr = myIP();
I also added <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> at the top of the same javascript code file. Now sessionAttr constant is called at line 60 of this code file (Note that I changed sessionAttributes: config.lex.sessionAttributes to sessionAttributes: config.sessionAttr).
When I try to load this page nothing shows up. if I do not make changes I described above then the page loads up correctly. So somehow I am making some mistake in my additions which is screwing this page.
NOTE: I am not at all familiar with JavaScript but based on a quick search I made the changes described above. I understand the issue is in the asynchronous call I am making and I went through this suggested link but I am unable to figure out the right structure. Can anyone provide me the right syntax so that the page loads up correctly and also returns the ip address of the client and sets it to sessionAttribute?
UPDATE: After some suggestions I made following changes to my code (link here - https://jsfiddle.net/ywdeu0o4/3/)
const configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {},
},
};
$(document).ready(function(){
configDefault.Bot.sessionAttributes.ip = myIP();
// undefined
});
function myIP() {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
//console.log(data.ip);
return data.ip;
});
}
console.log("myVar:",configDefault.Bot.sessionAttributes.ip);
When I run this code after opening the console I get undefined value for configDefault.Bot.sessionAttributes.ip. Why is it coming as undefined and not the ip address?
Open the browser dev tool (F12). Very likely you will see an error in the console. For instance the data is already an object, no need to JSON.parse it.
Then there's the asynchronous nature of ajax as Mikael already pointed out. Use a callback function to do something with the data.
EDIT: there was already a link to a page explaining how to use a callback, but maybe it was too much to figure out. You should learn about variables, functions, variable scope, callbacks and async behavior.
Basically you could replace that return with code that updates your global object, and do stuff... or create a new function that you can call back:
const configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {},
},
};
$(document).ready(function() {
myIP();
});
function myIP() {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
// after succesful ajax response call myCallback with data.ip
myCallback(data.ip);
});
}
function myCallback(theIP) {
// do your stuff here
console.log("Data.ip:", theIP);
configDefault.Bot.sessionAttributes.ip = theIP;
console.log("ConfigDefault:", configDefault);
};
Example: https://jsfiddle.net/bvevqdb1/
You can also call the callback without passing parameters and without (). That would pass the whole ajax result to the callback, and you can then process it there:
https://jsfiddle.net/bvevqdb1/1/
This seems to work fine for me: https://jsfiddle.net/ywdeu0o4/1/
$(document).ready(function(){
myIP();
});
function myIP() {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
console.log(data.ip);
return data.ip;
});
}

Javascript inline function call from callback [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Javascript closure not working
(1 answer)
Closed 5 years ago.
I have a function with a callback that checks whether or not a file exists on my server, with the result returned being either "true" or "false". My problem is that i am calling this "DoesFIleExist" function in a for-loop with the "id" calculated earlier in the function. The problem is that whenever one of the function calls is resolved and tries to call "AddResultToPage" it uses the id of the last for-loop iteration, when it should be using the id it was given when the function was called.
The "DoesFileExist" function takes a path and a callback as parameters.
Any help would be much appreciated, as i have looked online and on here but most of the answers i have found are relating to buttons and event listeners on the buttons.
DoesFileExist('/XML/'+id.trim()+'.xml',function(data) {
console.log(id.trim()+" "+data);
if (data == "true") {
(function () {
console.log("adding to page - "+id.trim());
AddResultToPage(id,false);
})();
}else{
console.log("the file does not exist");
}
Put it in a self invoking function:-
(function(id){
DoesFileExist('/XML/'+id.trim()+'.xml',function(data) {
console.log(id.trim()+" "+data);
if (data == "true") {
(function () {
console.log("adding to page - "+id.trim());
AddResultToPage(id,false);
})();
}else{
console.log("the file does not exist");
}
})}(id)) // now, your inner code has reference to correct id due to closure
What happens is, by the time your response from server is received, the for loop had been completed and id gets set to last value.
With closure, id will refer to the value passed in the function and not the one in loop
You can use a specificId with let (that will stay in your scope, it is ES6). There is a related SO post about closures :
How do JavaScript closures work?
DoesFileExist('/XML/'+id.trim()+'.xml',function(data) {
let specificId = id;
console.log(id.trim()+" "+data);
if (data == "true") {
(function () {
console.log("adding to page - "+specificId.trim());
AddResultToPage(specificId,false);
})();
}else{
console.log("the file does not exist");
}

Get Data out of JQuery Function $.getJSON [duplicate]

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");
});

Trying to use JSON value outside $.getJSON function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript asynchronous return value / assignment with jQuery
I have the following javascript code, the time.php file has minute and hour output using json_encode function. If I move console.log inside the getJSON function it finds the correct values, however when I move it outside the function it shows as undefined.
var my_hour;
$.getJSON('../scripts/time.php', function(data) {
my_hour = data.hour;
});
console.log(my_hour);
The "$.getJSON" call is asynchronous; the interaction with the server takes time but the browser does not wait for it to finish. Thus, your code after the function call runs immediately, a long time before the callback runs.
it's because it's asynchronous. Ajax request made by $.getJson async call your script and variables my_hour is initialized after your console.log(my_hour).
If you want it to work that way, then you should put console.log in some setInterval.
http://www.w3schools.com/jsref/met_win_setinterval.asp
var interval = setInterval(function(){
if (my_hour != undefined){
console.log(my_hour);
clearInterval(interval);
}
}, 200);
But it's it's not a good practice anyway.., your code should be placed in callback function as mentioned above.
var my_hour;
$.getJSON('../scripts/time.php', function(data) {
my_hour = data.hour;
console.log(my_hour);
});

Categories