Getting backing bean value with Javascript

JSF/EL and HTML/JS doesn’t run in sync. Instead, JSF/EL run in webserver and produces HTML/JS which in turn runs in webbrowser. Open page in browser, rightclick and View Source. You see, there’s no single line of JSF/EL. It’s one and all HTML/JS. In place of your JS function, you’ll see:

function afterLoad() {    
    alert("0");
}

Exactly this JS function get invoked on complete of your command button action. So the result is fully expected.

Basically, you want to let JSF re-render that piece of JS.

<p:commandLink action="#{statusBean.getStatuses}" update="afterLoad" oncomplete="afterLoad()"/>
<h:panelGroup id="afterLoad">
    <h:outputScript>
        function afterLoad() {    
            alert("#{statusBean.size}");
        }
    </h:outputScript>
</h:panelGroup>

Depending on the concrete functional requirement, which you didn’t tell anything about, there may be more elegant ways. For example, RequestContext#execute(), <o:onloadScript>, etc.

Leave a Comment