开发者

Jquery real time input validation with $.post function

Hi Guys:

I am kind of new to Jquery and web development, so please just bear with me. I want to implement real time input validation with Jquery on my website. Maybe I have some syntax errors in this post, but I am sure I don't have any in my real code.

This is what I have, whenever the user inputs something that's not blank the error() will be called and make a post request to the server (PHP+MySQL) to check if the input value already exists. The error() is also used again when the submit button is pressed.

This works perfectly fine before I press the submit button. If I enter something that already exists, the form will not be submitted. But if I enter something that's new, I will still get the ("exists") text even though the data still gets inserted into the database. I will always get the ("exists") after ("success"). It seems like when I submit, the .post request from the error() is made after the form's .post request. Does anyone how to solve this bug? or another way to construct this type of input validation?? Thanks

$('.unique').change(function(){
    error($(this));
});

function error(obj)
{
    var ok = true;

    if(obj.val().length == 0)
    {
        alert('This field can not be blank');
        ok = false;
    }

    else
    {
        var data = "action=check&input=" + obj.attr('name') + "&value=" + obj.val();
        $.post('database.php',
               data,
               function(rep开发者_StackOverflowly){
                   if(reply == true)
                   {
                      alert("This " + obj.attr('name') + " already exists");
                      ok = false; 
                   }        
               });

    }
    return ok;
}

//When the user submits the form
$('#info').submit(function(){
    var ok = true;
    var data = 'action=insert&' + $(this).serialize();

    //Passes each input to the error()
    $('.unique').each(function{
       var temp = error($(this));
       ok = ok && temp;
    });

    if(!ok) return false;

    $.post('database.php',
           data,
           function(reply){
               alert(reply);
           });
});

<form id="info" name="info" action="" method="post">
   <input type ="text" class = "unique" id = "username" name = "username" class = "unique">
   <input type ="text" class = "unique" id = "email"    name = "email"    class = "unique">
</form>

//On the server
if(isset($_POST['action']))
{
    if($_POST['action'] == 'check')
    { 
        $query = sprintf("select * from Users where %s = '%s'", 
                                                                $_POST['input'],
                                                                $_POST['value']);
        $result = mysql_query($query);
        if(mysql_num_rows($result) > 0)
        { echo true;}

        else
        { echo false;}
    }
    else
    {
        $query = sprintf("insert into Users(username, email) values('%s','%s')", 
                    $_POST['username'],
                    $_POST['email']);
        if(!($result = mysql_query($query)))
            die(mysql_error());

        echo 'Success';
    }      
} 


I had this problem in the past to. You can avoid this to prevent default behavior:

$('#info').submit(function(e){
e.preventDefault();

var ok = true;
var data = 'action=insert&' + $(this).serialize();

//Passes each input to the error()
$('.unique').each(function{
   var temp = err($(this));
   ok = ok && temp;
});

if(!ok) return false;

$.post('database.php',
       data,
       function(reply){
           alert(reply);
       });
});

This will avoid the form actually being submit. If you still want to submit it when the ajax post is okay:

$('#info').submit(function(){
  var theForm = this;
  $.post('database.php',
       data,
       function(reply){
           alert(reply);
           theForm.submit();
       });
});


There are a couple issues that stand out immediately. First error function is always return false. Second $.post is asynchronous. This means it will continue on with the code execution while waiting for response from the ajax request. You can change that in jquery my using $.ajaxSetup({async:false}); prior to the $.post request.

Here's a code sample that should work correctly:

$('.unique').change(function(){
    error($(this));
});

function error(obj)
{
    var ok = true;

    if(obj.val().length == 0)
    {
        alert('This field can not be blank');
        ok = false;
    }
    else
    {
        var data = {
          action: 'check',
          input: obj.attr('name'),
          value: obj.val()
        };

        $.ajaxSetup({async:false}); // Force program execution to wait for ajax response 
        $.post('database.php', data, function (reply) {
          if (reply) {
            alert("This " + obj.attr('name') + " already exists");
            ok = false;
          }
          $.ajaxSetup({async:true}); // Setup ajax to be async again
        });
    }
    return ok;
}

//When the user submits the form
$('#info').live('submit', function(e){
    e.preventDefault();
    var ok = true;

    //Passes each input to the error()
    $('.unique').each(function(){
       ok = ok && error($(this));
    });

    if (!ok) { 
      return false;
    }

    $.post('database.php', 'action=insert&' + $(this).serialize(), function(r) {
      alert(reply);
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜