jQuery Validation Plugin: Setting error message for remote method
According to the documentation (or from how I understand the stuff written about it), the script response is evaluated as a JSON. Returning true implies that the field passed validation while return values such a false, undefined or null would mean it failed. The documentation also seemed to mean that I can return a string that will be used and displayed as its error message. Good, I'm running several server side validations on a particular field. It's best that I display the details on which validation check that field failed.
My script did return a string but it wasn't being used by the validation plugin - no error messages are being displayed. I knew, though, that validation failed since the form did not continue to submit. The PHP snippet kinda looked like this:
<br /> <?php<br /> echo 'Ugh... that is not allowed';</p> <p>
Peeking at the plugin and jQuery source took me to the jQuery.parseJSON() utility function. Reading the documentation for that function gave me a clue on what I was doing wrong. Echoing 'true' resulted to true and echoing 'false' resulted to false - as if the string was eval()ed. If I were to eval() 'some string', it would give me an error. But if I eval() '"some string"' (note the double quotes) instead, it evaluates as a string.
So, in order for my message to be parsed as string, I just wrap the output inside double quotes:
<br /> <?php<br /> echo '"Ugh... that is not allowed"';</p> <p>
And that fixed my problem. Note that you should enclose it ONLY with double quotes, not single quote. jQuery.parseJSON() requires the input to be a well-formed JSON string in order to parse it. For a valid JSON of a string, the string must be wrapped inside double-quotes (see http://json.org/).