Accessing onFailure method in Ajax call?

I’m fairly new to AJAX and am confused on one thing. Let’s say I’m making a call to a PHP script and want to do some error checking within the PHP script. I come across something that would cause an error and want to send the error message back.

var ajax = new Ajax.Request(FC.URL, {
				onSuccess: function(transport){
					var response = transport.responseText || "no response text";
					alert("Success! \
" + response);
				method: 'post', 
				parameters: params.toQueryString(), 
				onFailure: function(transport){
					var response = transport.responseText || "no response text";
					alert("FAIL! \
" + response);

The above code (I’m using prototype) “works” in my application in that I am correctly receiving the response text from the PHP script in the alert statement, however it is coming back in the onSuccess method and not the onFailure method. How would I force the PHP script to cause the AJAX call to use the onFailure method? Do I need to set certain headers from the PHP script or do something else?

onFailure does not describe that the script ajax is accessing is returning that there is a failure in the input. onFailure describes that ajax is unable to make the request.

If you really want to use this (which I don’t encourage btw, if your script can not be found be ajax, all input will be invalid!), you could try

if (input_is_invalid)
header(‘HTTP/1.1 500 Internal Server Error’);

That should do the trick and fire the ajax onFailure method.
Again, I strongly discourage you to use this. It’s better to use the onSuccess and handle incoming data. For example send a 1 from PHP if everything is fine, and a 0 if it’s not. Than check in javascript which value you got.

Ok that makes sense, but how would you pass over a flag like you mentioned above and an error message to be displayed? For example if someone enters a password that was too short my script would be returning “Password must be greater than 5 characters” - Would you just pass over a string with a delimiter in the format of:

0|My error message here

And use javascript to split that string? Or is there a better, “preferred” way to do that?

Using a string, your method sounds fine.
I usually use XML, then it would become something like

   <msg>The password you supplied is too short</msg>

But it seems to me this is just a matter of taste. I use XML because it has nice semantic markup. Strings are somewhat “flimsy” for my taste :slight_smile:

PS. If you are going for XML, don’t forget to send a “Content-Type: text/xml” to the browser before you start any output
PPS. If you are going for XML, use .responseXML instead of .responseText, get the message with .responseXML.getElementsByTagName(‘msg’)[0]