3

I want to execute a javascript method from server side. In my case, when i change a tab, in managed bean i want to call the javascript method. Is there any way to do this?

I tried using RequestContext. But it doesnot get called until the listener method finishes executing.

RequestContext executes a javascript after current ajax request is completed. I want to exceute the javascript method at the start of the ajax request.

The javascript method (which i want to invoke) is wriiten at the client side.

Went through http://metoojava.wordpress.com/2010/06/20/execute-javascript-from-java/ and http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html

But didnot find the solution to this problem.

Using jsf 2.1 and primefaces 4.0.

My code is

XHTML

   <p:tabView id="detailsId" widgetVar="detailsVar" >
        <p:ajax event="tabChange"  listener="#{mywBean.onTabChange}"/>
        <p:tab title="Service">
        </p:tab>
        <p:tab title="Books">
        </p:tab>
    </p:tabView>

<script>

function myJavascriptMethod() {
     alert("Hello All..");
     // Some functionality
}

</script>

Managed Bean

 public void onTabChange(TabChangeEvent event) {
        String tabId = event.getTab().getId();
        if(tabId.equalsIgnoreCase("Books")) {
           **need to call javascript method here**
          //Some Functionality
        }
    }

1 Answer 1

2

You can try:

String js="alert('Hello World!!')"; // write your javascript
RequestContext.getCurrentInstance().execute(js);

Javadoc:

http://www.primefaces.org/docs/api/4.0/org/primefaces/context/RequestContext.html#execute(java.lang.String)

Sign up to request clarification or add additional context in comments.

3 Comments

RequestContext executes a javascript after current ajax request is completed. I want to exceute the javascript method at the start of the ajax request.
Why not execute your javascript first and when it finished, call your Managed Bean?
You can use PrimeFaces remote command component (<p:remoteCommand>). primefaces.org/showcase/ui/ajax/remoteCommand.xhtml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.