Get data asynchronously JavaScript within for loop [duplicate] - javascript

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

Related

Why can't I update variables in this JavaScript class? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I'm writing a JavaScript class for an object that will get data via ajax on creation. The object and its retrieved data will then be available for use later on.
The problem is that the variables don't update with new values from the ajax call. They stay at whatever values they were initiated at.
Here's a simplified example of my code:
class Foo {
constructor() {
this.bar = 0;
this.makeAjaxCall();
}
makeAjaxCall() {
jQuery.get(
// ajax logic
)
.done(
function(response) {
this.bar = response.bar;
}
);
}
}
var bax = new Foo();
console.log(bax.bar); // outputs 0
I've confirmed that the ajax call occurs, both via the network monitor and by console logging the response variable. It's just that the change of variable value doesn't "stick". This also occurs with code later on, so I don't think the issue is me logging before the ajax call completes.
I suspect this is related to late bindings in JavaScript, but I haven't been able to wrap my head around that. Here's what I tried in that realm (it didn't work):
var bax_unbound = new Foo();
var bax = bax_unbound.bind(Foo);
console.log(bax.bar); // still outputs 0

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

Set variable inside AJAX callback function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I need able or disable a click event depending on the server result. I have the following funcion using jquery:
$("#button").click(function(){
var validated = true;
$.ajax({
url: "/Foo",
type: "POST",
success:function(data){
// alert(validated); ----> true
if(data){
validated = false;
// alert(validated); ----> false
}
}
});
// alert(validated); ----> true
return validated;
});
In the above code, always return true. I think the problem is that I set wrong the global variable validated. I have read this post and this but does not work for me. What am I doing wrong?
The problem is, that the AJAX call happens in a separate "thread" than the rest of the function. Thus, the thread with the click event runs on its own, does the AJAX call which is done ASYNCHRONOUSLY, and then returns. The AJAX thread never has the time to modify the validated var - the click handler has already returned.
The best way to solve this would be to make a callback from within the AJAX thread, or disable the element you want inside the AJAX thread itself, rather than returning a result to another function, which will then modify your button in another thread.

how to do a custom callback on a user function in javascript

I use callbacks all the time when using 3rd part libraries such as jquery, however I've run into an issue where I need to set up my own call back. Take for instance my current code:
// Get All Rates
function getAllRates() {
$('#shiplist tr.mainRow').each(function() {
var curid = $(this).attr("id");
var cursplit = curid.split("_");
var shipid = cursplit[1];
getRate(shipid);
});
}
This iterates through all the table rows that have class "mainRow", and each main row has the id of "shipment_#####" so for each row it splits by the _ to get the actual ship id, which it then uses to calla "getRate" function which sends an ajax call to the server using UPS or USPS api's to get the rate for the given shipment.
This works fine for UPS all rows start loading at once and return their rates independently. The problem is now with Stamps.com, they use an authenticated soap conversation so an authenticator string needs to be received from the first call and used in the next call and so on.
So basically I need to modify the above function to execute the "getRate()" function and wait for it to complete before executing the next iteration.
Anyone know how I can do this with out a lot of fuss?
EDIT - Clearification on the question being asked:
I want to take the following function:
getRate(shipid);
and access it like so:
getRate(shipid, function(shipList) { _Function_data_here_ });
When I define the getRate function, how do I define it so that it has that callback ability? how does that work?
I would suggest you extract all the IDs at once and pass them to your function. That way, you can easily process the first on individually and the rest afterwards. With deferred objects, this is really easy.
For example:
function extractAllIds(callback) {
var ids = $('#shiplist tr.mainRow').map(function() {
return this.id.split('_')[1];
}).get();
callback(ids);
}
function getRates(ids) {
var first = ids.shift();
$.ajax({data: first, ...}).done(function(response) {
// extract the authenticator string
for(var i = ids.length; i--; ) {
$.ajax({data: ids[i], ...});
}
});
}
extractAllIds(getRates);
In any way, you cannot make $.each wait for response of Ajax calls.

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