Wait Until Multiple Functions, Which May Or May Not Call Ajax Internally, Are Complete In JQuery?
I am currently validating a few inputs clientside. When the user submits the form, I want to check the values for the form inputs, and then do something once all the checks are com
Solution 1:
I don't see you validate_input
function return anything. If you want to wait, you need to return a promise, so that you don't pass undefined
to $.when()
:
function validate_input(input){
var value=input.val();
if (value.length<4){
return …; //code to execute if input is too short
} else {
return $.ajax({
// ^^^^^^
…
});
}
}
Solution 2:
var inputsLength = 0, // or maybe set it to $('form input').length
inputsReady = 0;
function checkInputsValidation(){
if (++inputsReady === inputsLength) YOURSALLINPUTSAREVALIDFUNCTION();
}
function validate_input(input){
inputsLength++; // remove it if you already set inputsLength
// blablabla
$.ajax({
type: 'get',
url: check_input_url,
data: input.serialize(),
success: function(data){
if (data=="invalid") {
//code to execute if invalid
} else {
checkInputsValidation();
}
}
});
}
Solution 3:
UPDATE: i just updated my answer. it is more likely to fit your needs now. i've added a parameter to the callback function.
use callbacks with anonymous functions and chain them:
1. add a parameter for the callback function and the callback function call:
function validate_input(input, callback){
value=input.val();
if (value.length<4){
//code to execute if input is too short
callback(false);
}
else {
$.ajax({
type: 'get',
url: check_input_url,
data: input.serialize(),
success: function(data){
if (data=="invalid") {
//code to execute if invalid
callback(false);
} else {
//code to execute if valid
callback(true);
}
}
});
}
}
2. when calling your function multiple times, chain it with anonymous functions (which are executed after success
in your $.ajax
-request has been fired):
$('form').submit(function() {
var input1 = $('form #input1');
var input2 = $('form #input2');
//validate both input values
validate_input(input1, function(result){
if(result == true)
{
validate_input(input2, function(result){
if(result == true)
{
//wait until all validation complete to execute code here
}
else
{
return false;
}
});
}
else
{
return false;
}
});
});
Post a Comment for "Wait Until Multiple Functions, Which May Or May Not Call Ajax Internally, Are Complete In JQuery?"