3

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

2 回答 2

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

于 2013-01-28T15:47:09.227 回答
0

Take a look at the Ajax Form Plugin http://malsup.com/jquery/form/.

For example, use it like this:

$(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,
    });
});
于 2013-01-28T15:23:36.127 回答