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.
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.
I think this is not possible.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With