简体   繁体   English

一起使用ajax,jQuery和php进行实时表单验证

[英]Using ajax, jQuery and php together for real-time form validation

Okay, so I have a form that a user will fill out, these are the username field, and a color verification field. 好的,我有一个供用户填写的表单,这些表单是用户名字段和颜色验证字段。 The username field automatically checks my database when the focus is changed to alert the user whether they're username is taken or not. 更改焦点时,用户名字段会自动检查我的数据库,以提醒用户是否使用了用户名。 The color verification field compares the color of the image displayed on screen to the color the user enters. 颜色验证字段将屏幕上显示的图像的颜色与用户输入的颜色进行比较。 If both of these fields are completed successfully, the button to register is displayed. 如果这两个字段都成功完成,则显示要注册的按钮。 This is the jQuery I am using 这是我正在使用的jQuery

$(document).ready(function()
{
    $("#username").blur(function()
    {
    //remove all the class add the messagebox classes and start fading
    $("#msgbox2").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
    //check the username exists or not from ajax
    $.post("checkusername.php",{ username:$(this).val() } ,function(data)
    {
      if(data=='no') //if username not avaiable
      { 
        $("#msgbox2").fadeTo(200,0.1,function() //start fading the messagebox
        {//alert(data);
          //add message and change the class of the box and start fading
          $(this).html('Your username was taken<? $_SESSION['test2'] = 0; ?>').addClass('messageboxerror') .fadeTo(900,1);
        });     
      }
      else 
      {
        $("#msgbox2").fadeTo(200,0.1,function()  //start fading the messagebox
        { //alert(data);
          //add message and change the class of the box and start fading
          $(this).html('User name is available!<? $_SESSION['test2'] = 1; ?>').addClass('messageboxok').fadeTo(900,1);  
        });


      }

    });

});
});

The php file for the above code is: 上面代码的php文件是:

session_start();
require("../db.php");
$username = $_POST['username'];

$sql ="SELECT * FROM user WHERE username = '$username'";
$go = mysql_query($sql,$db);
$numrows = mysql_num_rows($go);


if ($numrows) {
// no
echo("no");
} else {
// yes
echo "yes";
}

The second field for color is set up the same: 颜色的第二个字段设置相同:

$(document).ready(function()
{
$("#color").blur(function()
{
    //remove all the class add the messagebox classes and start fading
    $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
    //check the color is right or not
    $.post("checkcolor.php",{ color:$(this).val() } ,function(data)
    {
      if(data=='no') //if color is incorrect
      { 
        $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
        {//alert(data);
          //add message and change the class of the box and start fading
          $(this).html('Your color was incorrect<? $_SESSION['test1'] = 0; ?>').addClass('messageboxerror') .fadeTo(900,1);
        });     
      }
      else 
      {
        $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
        { //alert(data);
          //add message and change the class of the box and start fading
          $(this).html('Verification Successful<? $_SESSION['test1'] = 1; ?>').addClass('messageboxok').fadeTo(900,1);  
        });
      }

    });

});
});

The php file for the above code is: 上面代码的php文件是:

session_start();

$sescolor= $_SESSION['color'];
$usercolor = $_POST['color'];
$_SESSION['usercolor']= $_POST['color'];
$usercolor = strtoupper($usercolor);
if ($sescolor==$usercolor) {
    echo("yes");
} else {
  echo "no";
}

What I wanted to happen was for the two fields "username" and "color" to change the session variables of 'test1' and 'test2' based on they're state. 我想要发生的是使用“用户名”和“颜色”这两个字段根据状态更改“ test1”和“ test2”的会话变量。 So if username was invalid, test2 would be assigned a 0 instead of 1. Same for the color verification. 因此,如果用户名无效,则将为test2分配一个0而不是1。对于颜色验证,相同。 Then the idea was that I would have a seperate function check to see if both 'test1' and 'test2' were 1. If so, the user would see the submit button, if not, they would see an error message. 然后的想法是,我将进行单独的功能检查,以查看“ test1”和“ test2”是否均为1。如果是,则用户将看到“提交”按钮,否则,将看到错误消息。

This is what the "checkboth.php" would look like 这就是“ checkboth.php”的样子

$test1= $_SESSION['test1'];
$test2= $_SESSION['test2'];


echo $test1;
echo $test2;
if(($test1 ==1) && ($test2 ==1))
{
echo("yes");
}
else{
echo("no");
}

I am using the same jQuery structure for the third function. 我在第三个函数中使用了相同的jQuery结构。 This works, however, I always get back 'yes'. 这行得通,但是,我总是回“是”。 Upon a var_dump of the session, I find test1 and test2 to always equal 0. How do I go about accomplishing this? 在会话的var_dump上,我发现test1和test2始终等于0。我该如何完成这项工作? Thanks in advance! 提前致谢!

Why not use beautiful jquery validation plugin ? 为什么不使用漂亮的jquery验证插件 It has remote validation method . 它具有远程验证方法

I prefer ajax to post....after all, you're trying to do an asynchronous check of data without interrupting the UI experience. 我更喜欢用ajax发布...。毕竟,您正在尝试对数据进行异步检查,而不会中断UI体验。 That's the "A" in ajax. 那就是ajax中的“ A”。

$.ajax({
url: "checkusername.php",                   //
timeout: 30000,
type: "POST",
data: data,
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown)  {
    alert("An error has occurred making the request: " + errorThrown)
},
success: function(data){
        //do highlights
}
});

If you plan on using JSON as return data as I have shown, then you have to return json in your php doc. 如果您打算使用JSON作为返回数据(如我所示),则必须在php文档中返回json。 Right now, you've got it returning yes/no printed on the page, which would work if you specified your callback type as text. 现在,您已经在页面上返回了“是/否”,如果您将回调类型指定为文本,这将起作用。 Otherwise, using your method it's just going to get confused. 否则,使用您的方法会变得很困惑。

As to your color verification, I'd "stack" it in the success of the first as you can't have it happen until after the username is checked. 至于您的颜色验证,我会在第一次验证成功时将其“堆栈”起来,因为您必须先检查用户名后才能进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM