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);
});
Related
This question already has answers here:
How do I return the accumulated results of multiple (parallel) asynchronous function calls in a loop?
(5 answers)
Closed 6 years ago.
I have this function
function add_cnh(arr_clelem){
var id=arr_clelem.getElementsByClassName("present")[0].id;
var date=arr_clelem.getElementsByClassName("present")[0].getAttribute('date');
var tt_entry= arr_clelem.getElementsByClassName("present")[0].getAttribute('tt_entry');
//new Ajax.Updater('register', '/some_url', { method: 'get' });
new Ajax.Request('/attendances/new',
{
parameters:'id='+id+'&date='+date+'&timetable_entry='+tt_entry+'&subject_id='+subject_id,
asynchronous:true,
evalScripts:true,
method:'get'
/*onSuccess: function(transport) {
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
}*/
}
)
var ret=modal_data;
// $$('.MB_close').invoke('observe', 'click', _deinit);
return ret;
}
This function takes html-elements-object as an argument and basically render a modal-box and that modal box contain a form -elements which i need to store inside an array. The variable modal_data contains the elements which I require and its a global variable define in another file.
My problem is
This is a very old project using many JavaScript frameworks and libraries which date back to 2006 the library responsible for opening the model box itself is deprecated as can be seen here
And somehow I don't want to get into server side so I am using a for loop something like this
for(var i=0; i<arr_of_elements.length, i++)
{
my_arrvar[i]=add_cnh(arr_of_elements[i]);
}
Now with each itteration since I want the modal box to get closed and store the data within 'my_arrvar' which is somehow not possible as the call is asynchronous in nature and I've used closures and callbacks but no success. I don't want to use any sort of timer. So this is how it goes
Call the function and get data for each call and remove the modal box by id.
Also can this be used somehow and if then how?
You have to pass in ajax request asynchronous:false instead of true. Otherwise its not possible by another way.
Other Way using jQuery
The easiest way is to use the .ajaxStop() event handler:
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
});
See jQuery Event handler
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 do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
Im having an issue assigning a string to a variable and then returning it. It sounds simple and should be but im completely lost as to why what is happening is happening.
My code:
function drawpills() {
var picid;
$.post('js/fetchdata.php', function (data) {
var clock = document.getElementById('clock');
clock.innerHTML = "<img src='images/clock/pill.png' alt='pill_image' id='pillpic" + data + "'/>";
picid = "pillpic" + data;
alert(picid); //if i run it here i get pillpic31 which is what i want
});
alert(picid); //if i run it here i get undefined which is not what i want and which is what is being returned
return picid;
}
I highlighted the issue with comments on the respective line. Any help is appriecated.
Suggest you read through the linked article in comments.
What you need is something like this:
function drawpills(callback){
var picid;
$.post('js/fetchdata.php', function(data){
var pcid = data; // process pcid here
callback(pcid);
});
}
The problem is the asynchronous behavior of AJAX. When the AJAX response is sent, it moves onto the next statement, whether or not the call has finished executing. You can now do one of two things. You could either make the AJAX synchronous, which will probably break the timing of events on the page, or you could create a callback to be executed when the AJAX call is completely finished.
$.post callback is asynchronous function,so:
function drawpills(){
var picid;
var callback = function(data){
var clock = document.getElementById('clock');
clock.innerHTML="<img src='images/clock/pill.png' alt='pill_image' id='pillpic"+data+"'/>";
picid="pillpic"+data;
alert(picid);
}
$.post('js/fetchdata.php', callback);
//picid is undefined,because callback is running until server response data.
//unless you using synchronous request
alert(picid);
return picid;
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm trying to use $.get() to retrieve data from a server, and assign it to a variable to work with it. For example:
$.get('htmllink', {}, function(results){
//do stuff here
});
var morestuff = ; //$.get() data goes here
The problem is, I can't get anything to work outside the rounded brackets. Everything is treated as internal variables or something. What am I missing?
You need to do all of your processing inside the callback function. This is because the call to $.get only starts an asynchronous request, and then the next line (var morestuff = ...) is executed after the request starts, but before it has completed.
$.get('htmllink', {}, function(results){
//do stuff with results in here
});
The problem here is that the $.get request is asynch (Ajax), so there is a timing issue here. The
var morestuff =
will run before the Ajax call returns, so you won't have the value to assign.
You have to interact with the result of the ajax request in the call back to have access to it
$.get('htmllink', {}, function(results){
//all code that depends on results must run inside here
});
//you can't execute code here that depends on the Ajax call