Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Javascript variables from JSF [duplicate]

I have a JSF file that needs to get populated from the data I get from the JS function that I get from Ajax call to a web-service. The latter part works like a charm. I am able to retrieve the JSON data from the ajax call. I need to parse this json data and take data and use that to populate the JSF. I am unsure as to how I would access the JS variables from the JSF/xhtml.

Is is possible to do it in someway? I was going through some DWR stuff that would send ajax post from JS to the Java bean and I could use the bean variable from the JSF. But, I want to know if there is any other way of doing this.

I would greatly appreciate any help. I am using JSF 2.x btw.

Thanks, S.

like image 743
reg_frenzy Avatar asked Jan 19 '23 18:01

reg_frenzy


2 Answers

You can use the following 'hack' to get JS to submit information to JSF.

Create an invisible JSF form with <f:ajax> hook:

<h:form prependId="false" style="display:none;">
    <h:inputText id="input" value="#{bean.input}">
        <f:ajax event="change" execute="@form" listener="#{bean.process}" render=":something" />
    </h:inputText>
</h:form>

Let JS update the input field and trigger the change event:

<script>
    function somefunction() {
        var input = document.getElementById('input');
        input.value = 'your JSON string';
        input.onchange();
    }
</script>

Do the Java/JSF job in the listener method:

private String input; // +getter +setter

public void process(AjaxBehaviourEvent event) {
    doSomethingWith(input);
}

Put the desired JSF markup in a <h:someComponent id="something"> which will be re-rendered by <f:ajax render=":something"> when the listener has done its job:

<h:panelGroup id="something">
    The JSON string was: <h:outputText value="${bean.input}" />
</h:panelGroup>

That said, I'd prefer to do the webservice call in the constructor or action method of the managed bean instead of in JS. Your approach is literally a roundabout.

like image 103
BalusC Avatar answered Jan 28 '23 10:01

BalusC


I think this is not possible.

  • JSF runs on server.
  • JavaScript runs on client (browser).

So, JSF runs BEFORE action in JS.

Of course, you can make a servlet that will be called from JavaScript, receiving information stored in JavaScript variables. But, this will be in next step:

  • JSF assembles the page
  • JavaScript call WebService, getting JSON data
  • JavaScript send JSON data to server (servlet)
like image 42
Topera Avatar answered Jan 28 '23 09:01

Topera