Tuesday, December 20, 2011

Inform user about Ajax failed (no network) in Wicket

The problem

It is well known to the internet. If you have an Ajax application you have to somehow inform user in case Ajax fails. And in the modern world Ajax may fail very easily - WiFi switched off, bad smartphone connection et al.

Also we have a Wicket which does hide all the Ajax work behind the scenes - you drop components to the page, they do communicate via Ajax.

The (possible) solution
At least we employed the one for us.

1. Create the localized message key in the property file. We are using XML properties, so it'd look like Ajax failed! Reload please

2. Create a function in one of the javascript files you always load. You may do it inline, but the function in the file makes it easier to change. My guess it should survive absence of the Wicket too.

AlertError here is the generic error function showing jQueryUI custom dialog.


function tryRegisterWicketAjaxOnFailure(message) {
if (!Wicket || !Wicket.Ajax) {
return;
}
Wicket.Ajax.registerFailureHandler(function() {
alertError(message, 0, 'center', true);
});
}


3. As our tryRegister takes a message parameter we need to pass it from the Wicket. So, in your BasePage.java or whatever code just add


add(new HeaderContributor(new IHeaderContributor() {
public void renderHead(IHeaderResponse response) {
response.renderOnDomReadyJavascript(
String.format("tryRegisterWicketAjaxOnFailure('%s')",
getString("ajaxCommunicationFailedMessage")));
}
}));
4. Just enjoy it. You may put 'refresh' button, or a spinner at this dialog which would constantly check if the network is back. It's up to your creativity and demand.

No comments: