Success/Error Design Pattern For Ajax
'success/error' design pattern for Ajax requests is a JSON encoded string in a specific format - each response has a minimum of two elements in it - ie 'success' and 'error' - like this...
{
"success":"Task done successfully",
"error":false
}
OR
{
"success":false,
"error":"Database Connection Error!"
}
The success and error index don't have to be just a string - it can be a data structure - like this...
{
"success":{"words":['hello','world']},
"error":false
}
The return handler function will be something like this...
function ajaxReturn(data) { //data is the 'eval'ed object of the responseText
if(data.error) {
//The 'showErrorMessage' handles the error.
//showErrorMessage() will return true for a critical error and false for non-critical error.
if(showErrorMessage(data.error)) return;
}
//Else is not given - if there was a critical error, the function will return.
if(data.success) {
//Do whatever you want with 'data'
alert(data.success);
}
}
Advantages
- This method makes in possible to handle errors like Session Timeout and Database Connection Problems.
- Light-weight
- Support for critical and non-critical errors.
Disadvantages
- A bit more coding required
- This method fails if the net connection is lost.