Your issue is around deffered functions.
your success function in:
$.ajax({
url: 'ajax.php',
type:'POST',
data: data_string,
dataType: 'json',
cache: false,
async: false,
success: function(response){
callback(response);
}
});
Is defferred. Think of it as threaded. So the submit
continues without waiting for the callback to happen. So it doesn't call event.preventDefault()
, or more precisly, it does but it's too late, the submit has already returned.
I would change what ever is calling this from a submit button (which I'm guessing it is currently) to a normal button then validate it, then only submit the form if this validation succeeds using $('form').submit();
.
$('#button').click(function(event) {
var xxx = $('#xxx').val();
var yyy = $('#yyy').val();
var zzz = $('#zzz').val();
var uuu = $('#uuu').val();
if (zzz != '000000' && zzz != '') {
validate_xxxyyy(uuu, function(response) {
if (response === false) {
if (xxx == '') {
alert("XXX undefined!");
}
else if (yyy == '') {
alert("yyy Undefined!");
}
}
else {
$('#form1').submit();
}
});
}
else {
$('#form1').submit();
}
});
function validate_xxxyyy(uuu, callback) {
var data_string = 'uuu=' + uuu;
$.ajax({
url: 'ajax.php',
type:'POST',
data: data_string,
dataType: 'json',
cache: false,
async: false,
success: function(response){
callback(response);
}
});
}