简体   繁体   English

使用Jquery .post方法进行验证

[英]Using Jquery .post method for validation

Im making small project and now im working on the Registration module. 我正在制作小项目,现在正在注册模块上工作。 Im using Jquery .post method to call page that check if the entered data is correct. 我使用Jquery .post方法调用页面,以检查输入的数据是否正确。 Everything work fine but if the data is incorrect it show the message but also register the user. 一切正常,但如果数据不正确,它会显示该消息,但也会注册用户。 Here is the js code: 这是js代码:

$("#name").keyup(function(){  
  $.post("check/user_check.php" , {  
    username: $("#name").val()  
   }, function(response)    {  
     $("#validateTips").fadeIn("slow");  
     $("#validateTips").html(response);  
   });  
});

And the user_check.php is: 而user_check.php是:

<?php
include "config.php";
$user = $_POST['username'];


$user_query = mysql_query("SELECT username FROM users WHERE username='$user'");


if(strlen($user) < 3)
{
    print "<span id='wrong'>username is too short</span>";
}

There is other case for the too long and already taken but i gues you get what is the point. 还有其他情况,时间太长了,已经采取了,但是我想你明白了什么。 So the question is what to do to prevent registration if user_check.php print that username is incorrect? 因此,问题是,如果user_check.php打印用户名不正确,该如何防止注册?

Stop execution after you return the error message: 返回错误消息后,请停止执行:

if(strlen($user) < 3)
{
    print "<span id='wrong'>username is too short</span>";
    die(); //Stop right here
}

Well, you can solve it in a number of ways, but for starters, I suggest that you send your response as JSON instead of HTML and handle the formatting on the client side. 好了,您可以通过多种方式解决它,但是对于初学者来说,我建议您以JSON而不是HTML格式发送响应,并在客户端处理格式。

One easy way to distinguish between a success and an error is to set an appropriate HTTP status code on your server. 区分成功和错误的一种简单方法是在服务器上设置适当的HTTP 状态代码

In short, just set a 4XX or 5XX code on the sever, and you will end up in the jQuery ajax error / fail callback. 简而言之,只需在服务器上设置4XX或5XX代码,您将最终遇到jQuery ajax错误/失败回调。

Your code would look something like this: 您的代码如下所示:

$.post('check/user_check.php',{ username: $("#name").val() }).done(function(data)
    //handle success
}).fail(function(error){
    //handle failure
    console.log(error.responseText);
});

And in your PHP code, you simply set a status code that indicates an error when something goes wrong: 在您的PHP代码中,您只需设置状态代码即可在出现问题时指示错误:

header('HTTP/1.1 400 Bad Request', true, 400);

or if you're using PHP >= 5.4: 或者如果您使用的是PHP> = 5.4:

http_response_code(400);

I have posted a more detailed answer on this topic here . 我在这里就此主题发布了更详细的答案。

在您的jquery代码中使用off()(对于php为die())以停止执行off()的文档: http : //api.jquery.com/off/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM