get value from jquery ajax response without setting async false
I'm using jquery form plugin to submit data to server. Before su开发者_运维百科bmitting I'm running server side validation via ajax. so the structure is
function validateForm(formData, jqForm, options){
var check = true; //have to set check to false to avoid form submit
....
looping through form elements and putting values in to data array here
....
function sendData(callback){
$.ajax({
url:'validate.php',
data:data,
dataType:'json',
//async:false, if I uncomment this, code works as I want
success:callback
});
}
function processForm(response){
$.each(response,function(i,res){
//if validation is fail I'm setting check = false here
});
}
sendData(processForm);
return check;
})
Since I saw setting async to false is not good practice, how can I set the check value to false using callbacks?
Don't try to return the data. Do whatever work needs doing inside the callback (or in functions you call from it).
Have you seen the jQuery .submit()
function? You can cancel submission where validation fails by calling .preventDefault()
.
Example jQuery:
<script>
$("form").submit(function() {
if ($("input:first").val() == "correct") {
$("span").text("Validated...").show();
return true;
}
$("span").text("Not valid!").show().fadeOut(1000);
return false;
});
</script>
You could do your validation and submission in two phases - validate first, then use submit in an OnAJAXSuccess
handler.
精彩评论