使用mysqli_query进行ajax表单validation

到目前为止,我已经使用纯javascript来validation我的表单,但我需要在混合中添加一个mysqli查询。 只有我用jquery和ajax不是那么好。 我可以做一个简单的登录表单,但这有点复杂。 任何人都可以给我任何指针,我可以添加一个jquery / ajax组件来validation这个:

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. 

你能做的就是像这样发送$ .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函数以手动处理表单。 在这里你可以找到更多相关信息。

看一下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) { /*eg a upload percentage label */ //var percentVal = percentComplete + '%'; //$('#myLoadingDiv').html(percentVal); }, cache: false, }); });