Sunday, June 5, 2011

Asynchronous success and failure

Some background
I was working on a fix the other day that required some data changes in a web application backend without a page refresh. Pretty standard these days, nothing special here, that's AJAX, or asynchronous (I like to just say "asynchronous" because who uses XML anyways).

As I was working, I needed to know if my asynchronous post to the server was successful or failed.

Again, basic, you make a controller call, it forwards to a success or failure depending on what happened on the server. I don't mean a plain HTTP 500 failure, I mean a controller failure and the controller handled it and knows how to report on it in some way.

The bad
To my amazement, this simple success / failure concept was not in place. The simple fact that the asynchronous call triggered a success was the "success". I was unhappy.

First, the response page was "just some page", meaning is was an unrelated view that the controller was forwarding to. The page was HTML that is rendered in the browser for UI, not a data response.

Second, that's heavy, why do you need an HTML page to come across the wire to tell your UI that your asynchronous post was a success?

The success and failure views are very simple and vital to your asynchronous success callback. Here they are as JSON and are used relative to used jQuery AJAX.


This one is easy, success = "true", The controller was successful. Now you can carry on with whatever happy path occurs in the application.

"errorMessage":"display this message as error to user"

This one is easy, but has a little more to it.
  • success = "false", the controller failed
  • errorKey = ?, the controller failed because of this error, can be whatever key your application implements for tracing down error
  • errorMessage = ?, whatever message the UI should present to the user because of the error
The "errorMessage" being in the response gives you the advantage of managing the error text on the server and not in the browser, you can also make use of the localization of the text on the server in a single place. Your controller likely threw this exception and is reported in your application logs, its now shared to the UI.  

Both are light weight responses to your UI that allow you to act properly now in your success event. I used "true" and "false" in my JSON for the success value, you can use whatever value you want. The true / false limit gives it simplicity. Even if you are executing the controller via wget or curl, the response structure is more easily managed, verses some generic page load.

No comments:

Share on Twitter