I'm validating a form containing user profile information, and I want to check with my server to see if the user name specified by the user is already in use. I've defined a validation method like so:
$.validator.addMethod(
'check_username',
function(value, element, param) {
console.log('starting');
var name_is_in_use = 0;
// Start the throbber.
$('form#user-profile-form input#edit-name').addClass('searching');
// Hit the server and see if this name is already in use by someone else.
$.ajax({
url: '/checkusername/' + value + '/" . $form['#user']->uid . "',
dataType: 'json',
data: {},
async: false,
success:
function(data) {
console.log('back from the server');
name_is_in_use = data; // unnecessary, but whatever
// Kill the throbber
$('form#user-profile-form input#edit-name').removeClass('searching');
},
});
return name_is_in_use;
},
'Sorry, but this username is already in use.');
Overall, the validation process works; what I'm having trouble with is getting a "busy" throbber attached to the input field to work properly -- the throbber never changes from its regular state to its busy state. But after adding some sleep() calls back on the server to exaggerate what's really happening back there, what I'm seeing is that both of those console.log statements appear in the console at the same time -- after the call to the server has been completed. That explains why I'm not seeing the throbber change -- the .searching
class is removed immediately after it was added. But what I don't understand is why I'm not seeing what I think ought to be happening:
- I click the field in the browser to fire the validation method.
console.log('starting')
shows up in the console- The throbber gets turned on.
- There's a pause while the server gets called, sleeps a bit, and returns its value,
console.log('back')
shows up in the console- The throbber gets turned off.
Instead, I'm getting this (ignoring the throbber class changes):
- I click the field in the browser to fire the validation method.
- There's a pause while the server gets called, sleeps a bit, and returns its value,
console.log('starting')
shows up in the console, and then, with no delay,console.log('back')
shows up in the console
Steps 3 and 4 happen at virtually the same time.
I'm really puzzled about this -- it looks like the entire execution of the handler is getting held up by the ajax call, which makes no sense to me at all. Can anybody offer some insights? Thanks!