使用 mysqli_query 进行 ajax 表单验证

Posted

技术标签:

【中文标题】使用 mysqli_query 进行 ajax 表单验证【英文标题】:ajax form validation with mysqli_query 【发布时间】:2013-01-11 23:11:02 【问题描述】:

到目前为止,我已经使用纯 javascript 来验证我的表单,但我需要在组合中添加一个 mysqli 查询。只有我对 jquery 和 ajax 不太擅长。我可以做一个简单的登录表单,但这有点复杂。谁能给我任何关于如何添加 jquery/ajax 组件来验证这一点的指示:

foreach($_POST as $key=> $for) 

     if(!empty($for) && $key != 'send' && $key != 'title')  

        $usercheck =  "SELECT email FROM users WHERE email = '$for'";
        $usercheck = $db->query($usercheck);

     if($usercheck->num_rows > 0) $x="1"; continue;
     if($usercheck->num_rows == 0)$x="2"; break;
     
  

     if($x == "2") $message = $for." is not a regestered email";
     if($x == "1")   // valid - submit.

【问题讨论】:

【参考方案1】:

你可以这样发送$.post:

    $.post("test.php",  "post1": "something", "post2":"somethingelse" , // those will be sent via post to test.php
  function(data)// the returned data
    console.log(data.return1); // here just logging to the console. **optional**
    console.log(data.return2); 
    // complete your process 
  , "json"); // specifying the type as json also optional

在你的test.php

foreach($_POST as $key=> $for) 

 if(!empty($for) && $key != 'send' && $key != 'title')  

    $usercheck =  "SELECT email FROM users WHERE email = '$for'";
    $usercheck = $db->query($usercheck);

 if($usercheck->num_rows > 0) $x="1"; continue;
 if($usercheck->num_rows == 0)$x="2"; break;
 
  

 if($x == "2") $data['message'] = $for." is not a regestered email";
   echo json_encode($data); // echo to pass back to $.post .. json_encode() in case of using json
   
 if($x == "1")   // valid - submit
  $data['message'] = 'valid'; // pass the message as valid post
echo json_encode($data); 

记住:

如果您发布表单提交以将event.preventDefault() 添加到您的javascript 函数以手动处理表单。 here你可以找到更多。

【讨论】:

内容丰富,有很多值得尝试的地方。太感谢了。这对我来说非常有用。【参考方案2】:

看看 Ajax 表单插件http://malsup.com/jquery/form/。

例如,像这样使用它:

$(document).ready(function()  
    $('#myForm').ajaxForm(
    
        beforeSend: function() 

        ,
        success: function(response)
        
                //wow, it worked, let's do something with response
        ,
        uploadProgress: function(event, position, total, percentComplete) 
            /*e.g. a upload percentage label */ 
            //var percentVal = percentComplete + '%';
            //$('#myLoadingDiv').html(percentVal);
        ,
        cache: false,
    );
);

【讨论】:

非常感谢。这对我有很大帮助。非常感谢。

以上是关于使用 mysqli_query 进行 ajax 表单验证的主要内容,如果未能解决你的问题,请参考以下文章

ajax分页代码

ajax分页代码

尝试将 xampp 数据库表连接到 php:错误未定义变量:mysqli_query 和致命错误

mysqli_query 通过变量输入

mysqli_query函数的问题[重复]

mysql怎么删除一个表