简体   繁体   中英

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. Everything work fine but if the data is incorrect it show the message but also register the user. Here is the js code:

$("#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:

<?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?

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.

One easy way to distinguish between a success and an error is to set an appropriate HTTP status code on your server.

In short, just set a 4XX or 5XX code on the sever, and you will end up in the jQuery ajax error / fail callback.

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:

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

or if you're using 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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