tags:

views:

585

answers:

3

I build JQuery/JS/PHP/mySQL app with DB records management and need to provide reliable & complete feedback to the user on AJAX calls, modifying back end DB records. The problem IMHO is $.ajax success: and error: functions indicate just AJAX transport layer success and not the whole process. What if BD modification fails? How can one provide the complete feedback to the user?

I ended up with

$.ajax({
   url: "/action/delete",
   data: "rowid="+rowid,
   complete: function(xmlHttp) {
   if ( xmlHttp.responseText ) alert('Success - back end returned "success"');
      else alert('failure - back end returned NULL')
   }
});  

and PHP response:

$success = deleteRecord( $_GET(rowid) );

if($success) { 
   print 'success';
} else {
   print NULL; 
}
exit();

The idea is simple - if I manage to get positive feedback from the back end, then the whole operation succeeded, if not - user don't care where problem occurred.

Thank you in advance, your feedback is highly appreciated.

+3  A: 

If you respond to the request with some json data instead of just some new html to insert into the DOM, you can place whatever kinds of error codes and messages you like with the data. For example, if your response was something like...

{ 
    errorstate: 0,
    errormsg: "All systems are go",
    displaytext: "stuff I want to display when all goes well"
}

Your javascript code can examine this data and do whatever it feels it needs to. It also allows you to push more of the error handling into your server script which can often be simpler.

Try http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback

rikh
shouldn't you have braces around that rather than square brackets?
Tom Haigh
oops, yes, but you get the idea.
rikh
Thanks, Rikh - it looks like a good solution. Interesting however why AJAX do not provide feedback feature.
+2  A: 

One possible solution would be to use the HTTP response code to signal a failure, like 200 OK, everything's ok, and 500 Internal Server Error on error, which you can simply check when you reach state 4.

In PHP I believe this is done through header("HTTP/1.0 200 Ok") before any other data is sent. If you're afraid data will be sent by mistake before you can evaluate the correct header to set you can turn on output buffering.

How you wish to present the data is of course up to you, you could for example on 500 just have document.getElementById("myerrorbox").innerHTML = xmlHttp.responseText, or similar, and render a partial html-document in your php-program.

roe
A: 

I send status messages back to the client. Along with the error flag. And then my JavaScript code displays the message it got from the server, and colours the message according to the error flag. I find that to be quite efficient.

Jan Hancic