Sequential execution of Ajax requests [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
The script should take the user's session via ajax and transfer it to other ajax requests that take the data for the charts. The first request succeeds, but others have not, becouse sessionId for them is undefined. Tried to wrap them in a function, but unfortunately nothing happened. What can be done?
var sessionId,
requestInWorkCount,
requestInWorkPower;
function getSession(){
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonLoginUser?UserID=User1&UserPassword=123", {},
function(data) {
$.each(data, function (key, val) {
sessionId = val.toString();
return sessionId;
})
});
};
function getData(session){
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonGetIndicator?SessionID="+session+"&IndNum=1", {},
function(data) {
$.each(data, function (key, val) {
requestInWorkCount = val;
return requestInWorkCount;
})
});
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonGetIndicator?SessionID="+session+"&IndNum=2", {},
function(data) {
$.each(data, function (key, val) {
requestInWorkCount = val;
return requestInWorkPower;
})
});
};
$(document).ready(function(){
getSession();
getData(sessionId);
setInterval('show()',1000);
});

ajax call is async so your second ajax call is executed before the first completes thats the reason sessionId is undefined.
Use the success function of first ajax call and call GetData() in it.
Also you don't need to return sessionId
function getSession(){
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonLoginUser?UserID=User1&UserPassword=123", {},
function(data) {
$.each(data, function (key, val) {
sessionId = val.toString();
getData(sessionId);
})
});
};
you call like this now:
$(document).ready(function(){
getSession();
});

The AJAX request are asynchronous and you cannot execute them sequentially.
An easy solution here would be to call getData() inside AJAX success block:
function getSession() {
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonLoginUser?UserID=User1&UserPassword=123", {}, function(data) {
$.each(data, function (key, val) {
sessionId = val.toString();
getData(sessionId);
return sessionId;
});
});
};

You have to take the RESPONSE of the ajax request. You do not return it, I believe. But in your code you should perhaps do
sessionId = getSession();
getData(sessionId);
You forgot to dereference what it returned.

Related

Wait for chain of AJAX calls to complete [duplicate]

This question already has answers here:
jQuery callback for multiple ajax calls
(14 answers)
Closed 7 years ago.
I have a function that calls other functions which have AJAX requests. I want all of the AJAX calls to complete before calling the last function. I initialize an array and need all of the AJAX calls to have successfully completed before going to the last step. When I run the code in the browser the console is showing the last method being called before the first AJAX call is completed. I've tried using .done however I'm still getting the same result.
function Search() {
var userIds = [];
var certName = $('#certificationName').val();
var skillNumberOne = $('#skillName1').val();
var skillNumberTwo = $('#skillName2').val();
var skillNumberThree = $('#skillName3').val();
var locale = $('#location').val();
CertMatchResults(certName, userIds);
SkillMatchResults(skillNumberOne, userIds);
SkillMatchResults(skillNumberTwo, userIds);
SkillMatchResults(skillNumberThree, userIds);
LocationMatchResults(locale, userIds);
console.log(userIds);
DisplayMatches(userIds);
}
function CertMatchResults(certName, userIds) {
if (certName == '') return;
$.getJSON('json_data.php', { method: 'matchCerts', certName: certName }, function(data) {
$.each(data, function(key, value) {
console.log("Cert Match >>> " + value.user_id);
userIds.push(value.user_id);
});
}).done(function() {
console.log("Cert match completed.");
});
}
function SkillMatchResults(skillName, userIds) {
if (skillName == '') return;
$.getJSON('json_data.php', { method: 'matchSkill', skillName: skillName }, function(data) {
$.each(data, function(key, value) {
console.log("Skill Match >>> " + value.user_id);
userIds.push(value.user_id);
});
});
}
... other calls below ... I can add them if needed
DisplayMatches needs all of the AJAX calls in each of the functions before it to complete.
You should create a chain of deferred objects.
Each ajax call returns Deferred object and then you can gather them in jQuery.when function and invoke the last function once all the ajax calls resolved their promises in jQuery.then function.
$.when( $.getJson("url1"), $.getJson("url2") ).then(function( valueFromUrl1, valueFromUrl2 ) {
functionThatShouldBeInvokedLast();
});
Have all functions call the DisplayMatches when they are done and check the userIDs array if it is complete ... and when it is you know all is done so you just run it, if not, exit

javascript sync ajax call issue

i ma trying to fetch list of names of htmls from ajax call and then for each html another ajax call and then i am trying to append it using handlebar. but this is not happening with below code. can somebody help me in debugging it :
$.getJSON('api/filterTemplate/' + pageName.page, function (data) {
var promises = [];
$.each(data, function (i, rec) {
promises.push($.get('commonCore/templates/' + rec.templateHtml));
});
$.when.apply(this, promises).then(function() { //after all requests complete
$.each(arguments, function(i, html) {
var filterTemplate = Handlebars.compile(html);
replaceFilterTemplate(filterTemplate,data[i].classids);// this functions appends html to div -data[i].classids
})
})
});
after each html is fetched it should be appended and then next call should happen
$.get returns the jqXHR Object. That's what you're actually adding to your promises array.
You should use synchrone calls, or reformat your code to handle all the fetches async and then proceed through the promises.
Synchrone alternative:
$.each(data, function (i, rec) {
$.ajax({
url: 'commonCore/templates/' + rec.templateHtml,
async: false,
success: function(result) {
promises.push(result);
}
});
});

Overriding variable value inside the $.get() [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am facing a quite Strange problem, I dont seem to be able to override variable jSonData from inside the success function of $.get()
$.fn.name = function(data, options) {
var jSonData = data;
var settings = $.extend({
....
}, options);
if(typeof data !== 'object') {
if(settings.debug) console.log('Getting configuration settings from: ', data);
$.get(data, function(d) {
jSonData = d; //I attempt to override the value here
}, 'json');
}
console.log(jSonData); // Gives the same value as it was before
};
Note: The success event of the $.get() is triggered
By the time you logged the value, the $.get() has not overridden jSonData yet since the AJAX request has not returned by that time. Do the console.log inside the function instead.
$.get(data, function(d) {
jSonData = d; //I attempt to override the value here - You just did!
console.log(jSonData);
}, 'json');
I was having that problem because AJAX calls are asynchronous and thus the call would not have been completed when console.log() was executed.
Solution I used to fix my issue was by using deferring methods.
$.fn.name = function(data, options) {
var jSonData = data;
var settings = $.extend({
....
}, options);
var getData = function() {
if(typeof data !== 'object') {
return $.get(data, 'json');
}
else { return jSonData; }
};
getData().done(function(result) {
jSonData = result;
console.log(jSonData); // Gives the same value as it was before
}).fail(function() {
//
});
};

jQuery events after the $.post is happening before the request finishes [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the following code, and for some odd reason, the order in which the events are happening is not making sense to me. Is there anyway in which I can make it so that it goes in the order?
var vm_good = false;
console.log("Before", vm_good);
$.post("./ajax/call_price", {id: product_id}, function(data){
$.each(data, function(key, value){
$(".unit-price span").html(value);
});
vm_good = true;
console.log("Inside", vm_good);
enableNext();
}, 'json');
console.log("After", vm_good);
And the results on the console window is:
>Before false
>After false
>Inside true
>window.vm_good // I called it manually after the page loaded
>>true
$.post is a shorthand of $.ajax. A in AJAX stands for asynchronous, so interpreter will execute next command, while $.post will run your event handler (function(data)) when your request is done. If your request wouldn't be asynchronous then your browser would freeze, because it would wait for your request to finish.
You can use $.when(deffered).then(handler) to execute code after your request is done:
var callPrice = $.post("./ajax/call_price", {id: product_id}, function(data){
$.each(data, function(key, value){
$(".unit-price span").html(value);
});
vm_good = true;
console.log("Inside", vm_good);
enableNext();
}, 'json');
$.when(callPrice).then(function () {
console.log("After", vm_good);
});
.post() is an asynchronous request. that means JS doesn't wait for it to finish, it just move on to next instruction.
You need to put console.log("After", vm_good); inside your post callback like this-
var vm_good = false;
console.log("Before", vm_good);
$.post("./ajax/call_price", {id: product_id}, function(data){
$.each(data, function(key, value){
$(".unit-price span").html(value);
});
vm_good = true;
console.log("Inside", vm_good);
enableNext();
console.log("After", vm_good); // you should put this here
}, 'json');

How to return a value from a function that calls $.getJSON?

function lookupRemote(searchTerm)
{
var defaultReturnValue = 1010;
var returnValue = defaultReturnValue;
$.getJSON(remote, function(data)
{
if (data != null)
{
$.each(data.items, function(i, item)
{
returnValue = item.libraryOfCongressNumber;
});
}
});
return returnValue;
}
Why is the returnValue from this function alway equal to the default value set at the beginning of the function and never to the value retrieved from the JSON lookup?
If you don't want to use asynchronous function, better use the following:
function getValue(){
var value= $.ajax({
url: 'http://www.abc.com',
async: false
}).responseText;
return value;
}
This function waits until the value is returned from the server.
This happens because that callback function (function(data) {...}) runs later when the response comes back...because it's an asynchronous function. Instead use the value once you have it set, like this:
function lookupRemote(searchTerm)
{
var defaultReturnValue = 1010;
var returnValue = defaultReturnValue;
$.getJSON(remote, function(data) {
if (data != null) {
$.each(data.items, function(i, item) {
returnValue = item.libraryOfCongressNumber;
});
}
OtherFunctionThatUsesTheValue(returnValue);
});
}
This is the way all asynchronous behavior should be, kick off whatever needs the value once you have it...which is when the server responds with data.
The function you pass to getJSON is run when the response to the HTTP request arrives which is not immediately.
The return statement executes before the response, so the variable hasn't yet been set.
Have your callback function do what needs doing with the data. Don't try to return it.
const getJson = (path) => {
return new Promise((resolve) => {
$.getJSON(path, function (data) {
setTimeout(() => {
resolve(data);
}, 1);
});
})
}
var result = await getJson('test.json');
console.log(result);

Categories