Mark Stang
Mark Stang

Reputation: 51

Using Primefaces JavaScript to call a JSF method on a bean on the server

In the Primefaces User Guide it shows examples of how to make AJAX calls to the server

PrimeFaces.ajax.AjaxRequest('/myapp/createUser.jsf',
{
    formId: 'userForm',
    oncomplete: function(xhr, status) {alert('Done');}
});

What I can't figure out is how to call a particular method. My goal is to invalidate the session from the client using JavaScript.

Upvotes: 5

Views: 31288

Answers (3)

Cjxcz Odjcayrwl
Cjxcz Odjcayrwl

Reputation: 22847

RemoteCommand is a nice way to achieve that because it provides you a JavaScript function that does the stuff (calling backing bean, refreshing, submitting a form etc., everything that command link can do).

From PrimeFaces 3.4 documentation:

<p:remoteCommand name="increment" actionListener="#{counter.increment}"
out="count" />

<script type="text/javascript">
function customFunction() {
    //your custom code
    increment(); //makes a remote call
}
</script>

Upvotes: 18

wrschneider
wrschneider

Reputation: 18770

What I've typically done is put a hidden p:commandLink on the page, then have Javascript call the click() event on it.

<p:commandLink id="hiddenLink" 
   actionListener="#{bean.methodToInvoke}" style="display:none"/>

Then

$('#hiddenLink').click();

Upvotes: 4

BalusC
BalusC

Reputation: 1108722

Do it in the @PostConstruct method of the request scoped bean which is associated with the requsted JSF page by EL like #{bean}.

@ManagedBean
@RequestScoped
public class Bean {

    @PostConstruct
    public void init() {
        // Here.
    }

}

Unrelated to the question, I only wonder why you would ever do it that way? JSF/PrimeFaces offers much nicer ways using <f:ajax> and <p:ajax> and consorts.

Is it the intent to run this during Window's unload or beforeunload events? If so, then I have to warn you that this is not reliable. It's dependent on the browser whether such a request will actually reach the server or not. More than often it won't. Use it for pure statistical or premature cleanup purposes only, not for sensitive business purposes.

Upvotes: 1

Related Questions