mehere
mehere

Reputation: 1556

Invoke javascript method from server side

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
        }
    }

Upvotes: 3

Views: 1184

Answers (1)

BlackBlaze
BlackBlaze

Reputation: 254

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)

Upvotes: 2

Related Questions