小编典典

使用mysqli_query进行ajax表单验证

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.

阅读 306

收藏
2020-07-26

共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函数中以手动处理表单。在这里您可以找到更多关于它的信息。

2020-07-26