3

I'm following this article in order to validate my form

My problem is when I have to use the remote method, e.g. remote: "check-username.php"

Since the documentation for remote method is not so clear for me, I would know:

How I need to structure my json output in php script?

2 Answers 2

15

To use the default method for remote, the remote page must respond with a string value of "true" or "false".

Valid (success) Must be:

echo "true";

Invalid (failure):

echo "false"; // this can be any false. eg: 0 , "" , NULL.

The response will be evaluated as JSON.

To apply an error message, other than the default for a remote response of invalid ("false"), add the input name to the validator options messages object like so.

rules:{
    username:{
        remote: "check-username.php"
    }
},   
messages:{
    username:{
        remote: jQuery.format('{0} is already in use, please choose a different name')
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

i received an error/warning 'jQuery.format' is deprecated. use jQuery.validator.format instead. which worked for me. thanks
Great finally the right answer!! the problem was in the server response, the right way is to return or echo "true" or "false" Thank you!
sorry for late comment.... so if email exists already, 'false' is sent? I'm a bit confused..
1

You don't need JSON. You can put any text. For example you can

echo "success";

for passed validation, and enter validation message like:

echo "Username already exists.";

for failed validation.

In your callback do something like this:

remote: {
           url: "check-username.php" ,
           type: "post" ,
           data: {
              username: function() {
              return $("#username").val();
           },
           complete: function(data){
                if( data.responseText != "success" ) {
                   alert(data.responseText);
                   //handle failed validation
                }
             }
         }

3 Comments

Thank you @argonius. I implemented I little variation than your suggestion. I returned true instead of success.
"true" is required, not "success",also the data:{} is not needed if the field name is 'username'
the right answer is the manta's one, the server should respond with "true" or "false"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.