Why do you think it's not working? If you're expecting your function to check and return a value before a form is submitted, it is likely that the availability function is returning before the ajax check is performed, allowing your form to submit and nullifying the alert -- i.e., the page is already unloaded and the new request is being processed. If you want to use this to check availability before submitting a form you'll need to:
Return false from availability (or otherwise stop the form submission)
Do the form submission from the availability success function.
(maybe) Indicate that you're expecting a text response instead of html.
You can also simplify the check -- there's no need to put "data" in a variable before you check it. I'm also not sure why you are adding it to the page, but that could be reasonable. I'd also suggest a name change for the function (if you modify it to do this) and handling the form submission via AJAX -- if not, you can remove the handler and simply trigger a submit on the form.
submitIfAvailable: function(form, element, value) {
$.ajax({
type: "GET",
url: "/tunnel/availability.php",
data: "username="+element,
dataType: 'text', // I think it should work without this, but...
success: function(data){
if (data == "yes"){
$form = $(form);
$.post( $form.attr('action'), $form.serialize(), function(result) {
// process the result of form submission
});
}
}
});
return false;
}
I'm making some assumptions -- modify as appropriate if this doesn't fit in with how the availability function is used. The key thing to remember is that the function will return before the AJAX call completes and you can't use any return value from the function that comes from the AJAX call. This is true, at least, if you don't force the AJAX call to run synchronously by setting the option aSync to false.