Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a string with remote using the jquery validate plugin

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");
    }
like image 303
nsw1475 Avatar asked Jul 21 '26 00:07

nsw1475


1 Answers

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 =>.

like image 150
carpeliam Avatar answered Jul 23 '26 15:07

carpeliam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!