returning a string with remote using the jquery validate plugin

浪尽此生 提交于 2020-01-04 03:59:29

问题


From the jquery documentation, describing the remote function of the jquery validate plugin:

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.

I have a php page that echo's a response, and it works as described if I use echo("true") or echo("false"). However, whenever I echo a string, no error message is displayed, not even the default message. What must I do to echo back an error message and have it display in the error label next to the input box being validated?

here is my jquery function:

$(document).ready(function(){
    $("#masq").validate({ 
        rules: { 
             user: {
                required:true,
                minlength:1,
                remote:"<?=$_SERVER['PHP_SELF']?>?action=remoteCheck"
             }
        }, 
        messages: { 
            user: "id must have at least 1 character."
        } 
    });         
 });

and my php function:

//sql validation here
    if(!$user) {
        $return = "id " . $user . " does not exist."; 
        //echo("false"); works correctly
            echo($return); //does  
    }
    else {
        echo("true");
    }

回答1:


I can confirm that if your server returns valid JSON (not just valid JS), returning a string is possible. In Ruby on Rails, I was able to accomplish this via "my string".to_json, which takes care of any escaping necessary. Not sure what the PHP approach would be. A JSON string needs to be doubly quoted, like this: 'My name is "Liam"'.to_json => ""My name is \\"Liam\\""". Whatever your server platform, you'll need to provide strings that look like what's on the right side of that =>.




回答2:


I struggled with this too (I need to pass more than one value to it, and depending on which conditions return false, show concatenated error messages, but that's for another SO posting) , but like I did initially, you are misunderstanding what the documentation says - it can ONLY return true or false (because it's being passed in JSON format) - the "string" it is referring to is if you use the messages: code, and then specify a message related to your error:

Here's an example (with comments):

$("#MemberInfo").validate({
    errorPlacement: function(error, element) {
           error.insertAfter(element);
       },
    rules: {    
        Memberemail: {
            required: true,
            email: true,
            remote: "checkReg.cfm"
        },

    },
    messages: {
        Memberemail: {
            required: "Please enter a valid email address",
            remote: jQuery.validator.format("{0} is already registered")    
        }
    }
});

The server side code returns "true" or "false", and the {0} in the message puts the value passed to the server-side script from the form, and prints out that plus the rest of the custom error message in the error that appears next to the field.

I'm still learning JQuery, so I hope this helps you or anyone else out, if it's still an issue for you!




回答3:


As the documentation states, you need to output valid JavaScript, so quote your string (and don't forget to escape if your ID might have quotes or whatnot in it):

$return = "\" id" . $user . " does not exist.\"";

You wouldn't type

var foo = id 2 does not exist.;

in JS either, would you?




回答4:


I entered a bug into github, but this should answer your question.
Its not ideal, but it will get your stuff to work

Scenerio
Comparing a date on the form to a date in the database.
Used remote to call a method in PHP Lithium framework.
Response is a json object {"data" : "true"} or {"data" : "please enter a date greater then xx/xx/xxxx"}

This fails miserably.
Tracing it through shows it short circuits while doing the post ( I think).

If I pass back just a string "true" or "false" it works fine.
If I pass back "some kind of message" instead of false, it also breaks.

The documentation says I should be able to pass back a message, well, if I pass anything other then a boolean, it breaks.
I'm not sure if I also need to add a header or something?

Work around
I downloaded the actual source file (instead of using cdn) I modified line 976 and 985 from response to response.data and used my original json object.



来源:https://stackoverflow.com/questions/2967398/returning-a-string-with-remote-using-the-jquery-validate-plugin

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