I'm using the jQuery validation plugin, which is very impressive. I define some custom validation methods with custom error messages, and all works well. I just write a function that takes the value of an input element, and the element itself, and specify that function in rules for elements with a given name
attribute. The function must return true
if the element is valid, and false
if it is invalid.
But now I need to do a validation that involves an ajax call. I use code like this:
let retval = true;
$.get(`url`, function(data) {
console.log( "success: ");
console.log(data);
retval = true;
}).fail(function(data) {
console.log( "error: " );
console.log(data);
retval = false;
})
return retval;
The idea being to let the result of the ajax call determine whether the validation method returns true or false. But stepping through it in Chrome developer tools, the return statement is never reached. So the .fail()
function that sets retval to false has no effect: stepping off the end of the .fail()
function goes into jQuery code, and the validation method returns true. How can I get the function containing the ajax call to return a value that reflects the status of the call?