How to wait until multiple ajax requests are done? - javascript

I have some async ajax requests
$.ajax({
url: 'first.php',
async: true,
success: function (data) {
//do stuff
}
});
$.ajax({
url: 'second.php',
async: true,
success: function (data) {
//do stuff
}
});
...
$.ajax({
url: 'nth.php',
async: true,
success: function (data) {
//do stuff
}
});
I want to run console.log() when every request is done.
I usually write this code:
$.ajax({
url: 'first.php',
async: true,
success: function (data) {
$.ajax({
url: 'second.php',
async: true,
success: function (data) {
//till the last ajax
}
});
}
});
However someone suggest Promise.all([]).
If I had to run, lets say, 4 ajax requests, which method would be the best/quickest?

Use Promise.all().
var promises = [];
promises.push(new Promise(done=>{
$.ajax({
url: 'first.php',
async: true,
success: done
});
}));
promises.push(new Promise(done=>{
$.ajax({
url: 'second.php',
async: true,
success: done
});
}));
promises.push(new Promise(done=>{
$.ajax({
url: 'nth.php',
async: true,
success: done
});
}));
Promise.all(promises).then(()=>{
console.log("All ajax completed.");
});

The official jQuery documentation states that:
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).
jQuery.when():
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
So you can do something like:
jQuery.when(
$.ajax({
url: 'first.php',
async: true,
success: function (data) {
//do stuff
}
}),
$.ajax({
url: 'second.php',
async: true,
success: function (data) {
//do stuff
}
}),
...,
$.ajax({
url: 'nth.php',
async: true,
success: function (data) {
//do stuff
}
})
).then(function() {console.log(...);});

Related

How to use javascript promises ES6 instead of jQuery ajax call?

I was trying to understand how promises works in javascript but I didn't found clear info about this, I would like to know if it possible and it is so how to do this using promises instead this code (equivalent)
$.ajax({
type: 'post',
cache: false,
url: 'myfile.php',
data: { info: info },
datatype: 'json',
success: function(response) {
console.log(response);
}
});
I ask this because I want to use only javascript without any framework or plugins, I have no problem with the other new feautures of ES6 just with this one, I hope you can help me, thanks.
You could do it like this
function doAjax() {
return $.ajax({
type: 'post',
cache: false,
url: 'myfile.php',
data: { info: info },
datatype: 'json',
});
}
doAjax.then(function(data) {
// do success stuff
}).fail(function() {
// do fail stuff
});
You have to wrap your ajax call with a function that instantiates and returns a promise:
function getSomething() {
return new Promise((resolve, reject) => {
$.ajax({
type: 'post',
cache: false,
url: 'myfile.php',
data: { info: info },
datatype: 'json',
success: function(response) {
resolve(response);
},
error: function() {
reject("some errors");
}
});
});
}
Then you consume your promise like below:
getSomething()
.then(response => console.log(response))
.catch(err => console.log(err));

Call function after ajax load()

I initiate a function after an ajax load(), but the function I intimate calls upon an additional function, which isn't working. How do I initiate ajaxstuff() after load()?
function ajaxstuff(data) {
$.ajax({
type: "POST",
url: "do-it.php",
data: {data},
success: function() {
console.log('I got this far'); // this doesn't work / isn't called
}
});
}
function doit() {
$('form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
console.log('I got this far'); // this works
ajaxstuff(formData);
}
}
$('.popup-loader').click(function() {
$(this).append('<div class="popup"></div>');
$('.popup').load('popup.php', function() {
doit(); // this works
}
});
Check for errors in your console, also, in your AJAX add an async option. set it to FALSE ("Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called"):
function ajaxstuff(data) {
$.ajax({
async: false,
type: "POST",
url: "do-it.php",
data: data,
success: function(result) {
console.log(result); //check in your console for errors
}
});
}
Syntax error in ajaxstuff function. data: {data}, , probably should be data: data,
Also when you're passing a FormData object to $.ajax, you have to specify processData: false and contentType: false
$.ajax({
type: "POST",
url: "do-it.php",
data: data,
processData: false,
contentType: false,
success: function() {
console.log('I got this far');
}
});

ajax - return and prevent deferred.then() execution

I have a AJAX request like this:
$.ajax({
type: 'GET',
url: url,
dataType: "json",
success: function(data) {
// ...
callbak(true);
},
})
.then(
function( response ) {
// ...
});
I'd like to run that callback function and so exit from that ajax request in success function and prevent deferred.then() execution.
In my case the callback is fired but after that deferred.then() is also executed and I don't want this to happen.
Any idea?
Thanks
Use a flag like so:
var executeThen = true;
$.ajax({
type: 'GET',
url: url,
dataType: "json",
success: function(data) {
// ...
executeThen = false;
callbak(true);
},
})
.then(function(response) {
if(executeThen){
// ...
}
});

How to wait until .done() is done before proceeding

I want to execute $(".foo").fadeIn("slow"); after everything from .done() is done.
Right now whenever the fadeIn is called I can still see how the text is being changed live because jQuery doesn't wait until it's done with that.
How would I go about doing that?
$(".notice").fadeOut("slow", function() {
$.ajax({
url: "http://graph.facebook.com/name",
cache: false,
dataType: "JSON"
})
.done(function(data) {
$(".foo .bar").text(data.name);
});
$(".foo").fadeIn("slow"); //
});
Put your code inside the callback of the jQuery.done method
$(".notice").fadeOut("slow", function() {
$.ajax({
url: "http://graph.facebook.com/name",
cache: false,
dataType: "JSON"
})
.done(function(data) {
$(".foo .bar").text(data.name);
$(".foo").fadeIn("slow"); //
});
});
Move it into your ajax-done function:
$(".notice").fadeOut("slow", function() {
$.ajax({
url: "http://graph.facebook.com/name",
cache: false,
dataType: "JSON"
})
.done(function(data) {
$(".foo .bar").text(data.name);
$(".foo").fadeIn("slow"); //move it here and it will be called if your ajax request is ready
callMethod(); //alternative you can call a mehtod
});
});
function callMethod() {
$(".foo").fadeIn("slow");
}
You can use a chain of done:
$.ajax({
url: "http://graph.facebook.com/name",
cache: false,
dataType: "JSON"
}).done(function(data) {
$(".foo .bar").text(data.name);
}).done(function() {
$(".foo").fadeIn("slow");
});
DEMO.

Why can't I do .ajax ( return data; )? jQuery

I'm trying to get my function to return the data it got into another function but it doesn't seem to work? How can I get it to return the data?
function playerid(playername) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
//$("#test").text(data);
return data;
}
});
}
I want to use it in another function like this
showBids(playerid(ui.item.value));
function showBids(playerid) {
$.ajax({
type: "POST",
url: "poll.php?",
async: true,
dataType: 'json',
timeout: 50000,
data: "playerid="+playerid,
success: function(data) {
//.each(data, function(k ,v) {
//})
//$("#current_high").append(data);
setTimeout("getData()", 1000);
}
});
First of all, your playerid() does not return anything, so what do you want to use? It has only $.ajax() call in it, no return statement (one of the callbacks in $.ajax() has return statement, but see below).
Secondly, JavaScript does some things asynchonously, otherwise every interface element would need to wait to react to user action until the AJAX call returns from the server.
Use event-based approach, by passing callbacks to some functions. Then, after they finish, just call the callbacks passing them the result:
function getplayerid(playername, callback) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
//$("#test").text(data);
callback(data);
}
});
}
and then use it like that:
getplayerid(ui.item.value, showBids);
(notice function name change since it does not actually return player ID, it gets it and passes it to callback)
You could try to use syncronous Ajax:
function playerid(playername) {
return $.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
async : false //making Ajax syncronous
}).responseText;
}
Otherwise you need to use showBids function as callback:
function playerid(playername, callback) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
callback(data);
}
});
}
//Usage
playerid(ui.item.value,showBids);

Categories