How to respond to jQuery Validation remote?

ぐ巨炮叔叔 提交于 2019-12-13 08:28:42

问题


Looked at multiple SO questions and the manual, but can't find it out. When I have

$( "#myform" ).validate({ 
    rules: {
    email: {
      required: true,
      email: true,
      remote: "check-email.php"
    }
  }
});

How should my check-email.php respond? I already tried echo "true", echo true, echo {error: true}, but it's not giving the right error message.

EDIT

I currently have my php set up as:

$query = mysql_query("SELECT id FROM users WHERE email='".$_POST['email']."'") or die (mysql_error());
if(mysql_num_rows($query)!=0){
echo json_encode(false);
}else{
echo json_encode(true);
}

However, it's always returning true...


回答1:


Quote OP:

How should my check-email.php respond? I already tried echo "true", echo true, echo {error: true}, but it's not giving the right error message.

That's because true will not trigger an error message... it is the opposite response.

  • true is the proper response for when it's valid (no error message).

  • If the response is false, null, undefined, or a string (error message) the field is evaluated as invalid.

Quote Title:

How to respond to jQuery Validation remote?

You should read the documentation:

The serverside resource is called via jQuery.ajax (XMLHttpRequest) and gets a key/value pair corresponding to the name of the validated element and its value as a GET parameter. The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.


EDIT:

As per edits and comments...

  • OP is using $_POST['email'] in his PHP. However, the documentation above states that the remote method uses GET by default.

  • If you want a customized error message, then you need to follow the documentation above... so within your PHP, instead of returning false... construct the message and return it within a string.



来源:https://stackoverflow.com/questions/20040605/how-to-respond-to-jquery-validation-remote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!