I have a small javascript function to validate my form on submit.
With that i do some basic validation to check things are not empty. There is a also an ajax/json request that returns either a 1 or 0 if a person is over 18 or not.
all works fine except the json part will not return valid to the rest of the script, its just local to that part and for the life of me i cannot figure out how to get it to work.
function validate_form() {
valid = true;
//Set varialbles
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var email = $('#email').val();
var comments = $('#comments').val();
var day = $('#day').val();
var month = $('#month').val();
var year = $('#year').val();
if ($('[name=photo]').val() == "") {
$('#formtext1').fadeOut('fast', function() {
$('#formtext2').fadeIn('fast', function() {
// Animation complete.
});
});
valid = false;
}
//check that terms have been accepted
if (myForm.terms.checked == false) {
$('#formtext1').fadeOut('fast', function() {
$('#formtext2').fadeIn('fast', function() {
// Animation complete.
});
});
valid = false;
}
if (firstname != "" && lastname != "" && email != "" && comments != "" && day != "" && month != "" && year != "") {} else {
$('#formtext1').fadeOut('fast', function() {
$('#formtext2').fadeIn('fast', function() {
// Animation complete.
});
});
valid = false;
}
$.getJSON('mydomainhere.com/dob_validate/' + day + '/' + month + '/' + year, function(result) {
//Check dob
var age = result.age
if (age) {
//Do nothing
} else {
valid = false;
}
});
return valid;
}
You need
var valid=true;at the top (or outside to make it global) of your function. It looks like you are creating a local variable when you get the result back which goes out of scope after that code block.To make it async from my comment:
http://www.w3schools.com/js/js_variables.asp