Giving back errors from AJAX requests is not that easy all the time.
One possibility is to give back an Error Message by the AJAX Result,
but this is not that comfortable at any time you have to put an error handling inside your AJAX call which is returning the message to the user.
Another solution are session based error messages for that you have to implement an Ajax error handling class.
For this messages you create a div layer inside your HTML.
<div id="messagefield" style="visibility: hidden;">
<a href="#" onclick="CloseMessageField()">close</a>
<div id="messagefieldtext"></div>
</div>';
<?PHP if($strMessageText){
echo "<script type='text/javascript'>
ShowMessageField()
</script>";
}
?>
This example is using Prototype.
<script language='JavaScript'>
function CloseMessageField() {
document.getElementById('messagefield').style.visibility = 'hidden';
}
function ShowMessageField() {
document.getElementById('messagefield').style.visibility = 'visible';
}
function RefreshMessageField(){
ajaxRequest=new Ajax.Request('/your/messege/ajax/url',
{ method:'get',
onSuccess: function(transport) {
if(transport.responseText.length > 1){
document.getElementById('messagefieldtext').innerHTML=document.getElementById('messagefieldtext').innerHTML+transport.responseText;
ShowMessageField();
}
}
}
);
}
</script>
Now you create an the AJAX Server by just returning simple HTML code instead XML you save some time
if(is_array($_SESSION['errors'] && count($_SESSION['errors']) > 0){
//returning the errors
foreach($_SESSION['errors'] as $strError){
echo $strError;
}
//reset the error string
$_SESSION['errors']=array();
}
Now you can give out Errors to a message window just by adding them to a Session like
$_SESSION['errors'][]="There has been an error by saving your entry"
or you can even use it to catch PHP Errors by using the
set_error_handler function to see the PHP Errors which were thrown during the AJAX request execution.
Any time you have a failed AJAX request you just call the RefreshMessageField() function instead from the returned AJAX response messages. Within your AJAX request you just have to differ between successful answer or showing the error message window.
This example is a bit simplified i wrote myself an own Error handling class which supports multiple reporting modes which differ between a Development mode and Production mode but this should give you an overview how the process works.