使用mysqli_query进行ajax表单验证

时间:2013-01-28 15:12:29

标签: php javascript jquery mysql ajax

到目前为止,我已经使用纯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.

2 个答案:

答案 0 :(得分: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您可以找到更多相关信息。

答案 1 :(得分:0)

查看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,
    });
});
相关问题