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()
:
functionvalidate_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;
functioncheckInputsValidation(){
if (++inputsReady === inputsLength) YOURSALLINPUTSAREVALIDFUNCTION();
}
functionvalidate_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:
functionvalidate_input(input, callback){
value=input.val();
if (value.length<4){
//code to execute if input is too shortcallback(false);
}
else {
$.ajax({
type: 'get',
url: check_input_url,
data: input.serialize(),
success: function(data){
if (data=="invalid") {
//code to execute if invalidcallback(false);
} else {
//code to execute if validcallback(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 valuesvalidate_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
{
returnfalse;
}
});
}
else
{
returnfalse;
}
});
});
Post a Comment for "Wait Until Multiple Functions, Which May Or May Not Call Ajax Internally, Are Complete In Jquery?"