Wednesday, June 26, 2013

Cancel JSF ajax call from javascript

suppose you have a jsf ajax attach to some UICommand like this

 <f:ajax ...></f:ajax>

How can you stop the ajax call in some situation? If you have control the source, you can always attach a onClick to the UICommand component. But in some situation, you do not have access to source. For example, the ajax is provided by some third-party component. You do not want to mess up with their components.

Here I come up a easy solution for this. First, I have a small js library.

var FxJSFBegin = "JSFBegin";
if (jsf) {
    var originalRequest = jsf.ajax.request;
    jsf.ajax.request = function(source, oevent, options) {
        var event = $.Event(FxJSFBegin);
        event.options = options;
        event.originalEvent = oevent;
        if (event.isDefaultPrevented()) {
        } else {
            originalRequest.apply(null, arguments);

This piece code proxies original JSF ajax call. It uses jQuery to fire a "JSFBegin" event. Integration code can listen this event using jQuery mechanism. Listener can cancel the jsf call using event.preventDefault().

  1. jQuery
  2. This piece code should be placed after jsf.js is loaded.

No comments:

Post a Comment