5

Having a problem where the form submits before the validateUsername function has a chance to complete the username check on the server-side.

How do I submit the form only after the validateUsername function completes? Hope this is clear...

form.submit(function(){
    if (validateUsername() & validateEmail() & validatePassword()) {
        return true;
    } else {
        return false;
    }
});         

function validateUsername(){            
    usernameInfo.addClass("sign_up_drill");
    usernameInfo.text("checking...");
    var b = username.val();
    var filter = /^[a-zA-Z0-9_]+$/;     
    $.post("../username_check.php",{su_username:username.val()},function(data) {
        if (data=='yes') {
            username.addClass("error");
            usernameInfo.text("sorry, that one's taken");
            usernameInfo.addClass("error");
            return false;           
        } else if (!filter.test(b)) {
            username.addClass("error");
            usernameInfo.text("no funny characters please");
            usernameInfo.addClass("error");
            return false;   
        } else {
            username.removeClass("error");
            usernameInfo.text("ok");
            usernameInfo.removeClass("error");      
            return true;    
        }
    });             
}   
2
  • 1
    Wow I frickin love this site! Thanks for the quick and concise responses. I plan to keep the client-side regex validation but move the username check to the server-side on submit.
    – Jung
    Commented May 15, 2009 at 2:26
  • scratch that...followed Adam and Pim Jager's advice, switched the form.submit to submit.click and rather than returning true, created a variable usernameIsOkay = true; submit.click(function() { validateUsername(); if (usernameIsOkay) { form.submit(); } });
    – Jung
    Commented May 15, 2009 at 19:18

7 Answers 7

10

More verbose version of Olafur's answer - The AJAX call is made and the function returns without waiting.

The callback doesn't finish until you've submitted the form.

What you should do is have the button/trigger calling the AJAX validation, and the callback should submit the form instead of returning true.

1
  • 3
    Yes indeed. Jung is looking for: $('#button').click( function() { $.post(.... function(){ if(stuff) $('#form').submit(); });
    – Pim Jager
    Commented May 15, 2009 at 9:34
1

The jQuery form validation plugin takes care of this for you -- I highly recommend it.

Some sample code:

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true
    },
    username: {
      required: true,
      remote: {
        url: "../username_check.php",
        type: "post",
        }
      }
    }
  }
});
1

I dealt with a similar issue recently. Under some circumstances, pressing enter on an input field might make the form submit. I attempted to remedy this in a number of ways, and then the specifications required changed so that pressing the Enter key or Go on a device, will allow a form submission. My solution was just what made sense to me at the time.

var form_submit = false;

function validateInput () {

    var field_value = $('#username').val();

    $.post('validation.php', {'input': field_value }, function (d) {
        if (d.valid) {

            form_submit = true;
            $('form').submit();

        } else {

            //error message or whatever

        }
    }, 'json');

}

$('form').submit( function () {

    if ( form_submit ) {
        return true; 
    } else {
        validateInput();
        return false;
    }

});
1

In jQuery there is a solution for the same. I need to check if a user exists or not in my application during some JavaScript. Here is the code:

var pars = "username="+ username;
var some = $.ajax({url: 'AjaxUserNameExist.php',
  type: 'GET',
  data: pars,
  async: false
}).responseText;


if(some=="1") //this is value Got from PHP
{
  alert("We cannot Go");
  return false;
}

if(some=="0")
{
  alert("We can Go");
  return true;
}   
2
  • 2
    Normally people frown on using synchronous logic in the browser, but in the case of (say) an onsubmit callback, this seems reasonable. Commented May 23, 2013 at 13:44
  • Some would still frown, and then proceed coding the submit through a callback ;-) Commented Jul 27, 2021 at 13:06
0

You can't return in an AJAX call. I suggest you read this section of the jQuery FAQ. Specially the part about callbacks. (the last code snippet)

-1

I suggest having

1) a hidden field in your form.
2) Set the value of it to 0 before you call any of the function that makes an AJAX request.
3) Increment the value when each of the function is successful in validating.
4) Set some number of seconds (i.e. amount of time/timeout it will take to complete all AJAX requests + a few seconds) to wait before checking the value of this hidden field. Check if the value is 3 (if there were 3 AJAX calls for validation) and let it submit then.

I guess, it will be better to do validation when the control looses the focus. Enable the submit button only when all controls pass the validation.

Sorry, I am not too familiar with JQuery but I will do this, if I were to use plain javascript.

-2

Why dont you just use $('#yourFormId').submit(); after you have received a result from your ajax backend?

1
  • 3
    because if that is inside the onsubmit event then it goes into an infinite loop Commented Mar 14, 2017 at 14:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.