I understand that AJAX is asynchronous, and all that. But I have the following code:
function doesUsernameExist(element)
{
// Check via AJAX (POST) if username already exists in the database
var funcReturned = null;
$.post(
'_ajax_checkexist.php',
{
var: 'username',
value: element.value
},
function(data) {
funcReturned = (data.toLowerCase() == 'exists');
},
'data'
);
return funcReturned;
}
I understand why the function isn’t returning a value properly, but what can I use as a workaround? This is for the Validity plugin, which requires a boolean returned by the doesUsernameExist function. I can’t do the usual workaround of having the $.post function alter some HTML element. It needs to return true/false to doesUsernameExist.
What kind of workaround can I use? I’m stumped by this.
If this is for validation purposes you will find that the jquery.validate plugin and its
remote ruleare perfectly adapted for what you are trying to achieve.So, instead of writing
doesUsernameExistfunctions and worrying about asynchronousness of AJAX and how to return values you will write validation rules for your form (which in fact is the final goal of the exercise => focus on the business and leave the plumbing to plugins):