neeraj
neeraj

Reputation: 480

jsf ajax call: executing javascript function in the end

I'm working with JSF 2.0 and here's my form:

<h:form id="fff" onsubmit="reloadMap();">
    <h:selectOneMenu value="#{rentCarPoolBean.state}">
        <f:selectItems value="#{rentCarPoolBean.stateList}" id="stateList" />
        <f:ajax event="change" render="cities stateSelected" onevent="showAlert"/>
    </h:selectOneMenu>
    <h:selectOneMenu  id="cities" value="#{rentCarPoolBean.city}">
        <f:selectItems value="#{rentCarPoolBean.cityList}"/>
        </h:selectOneMenu>
    <h:outputText value="#{rentCarPoolBean.state}" id="stateSelected" />
</h:form>

And the javascript function:

<script type="text/javascript">
    function showAlert(data){
         if (data.status == "complete")
             alert(document.getElementById("stateSelected"));   
    }
</script>

What the above code does is on selecting a state from the first dropdown, it makes the ajax call and renders the 'cities' dropdown and the 'stateSelected' outputText.

Also, it calls the showAlert() javascript function.

What I want to do is call the javascript function after all the data is returned and both the dropdown and the outputText have been rendered.

But currently the javascript function is called before the elements are rendered and the alert displays null. How do we make the javascript function execute in the end?

Upvotes: 4

Views: 18715

Answers (2)

Vsevolod Golovanov
Vsevolod Golovanov

Reputation: 4206

Here:

alert(document.getElementById("stateSelected"));

you're specifying only JSF component id, but you need to give a full clientId. Here's a link explaining this.

Upvotes: 0

BalusC
BalusC

Reputation: 1108742

You need to hook on a status of success instead. This will run after the HTML DOM tree has been updated. The status of complete runs directly after the ajax response has been returned. This is admittedly a misleading status name, but you should try to interpret it in context of "HTTP request" like as the begin status.

Another problem is that the document.getElementById() selects items by the HTML element ID, not by JSF component ID. You need to give it exactly the ID as JSF has generated to the HTML. You can figure the right HTML element ID by viewing the page source in webbrowser.

All with all, your new function should look like this:

function showAlert(data){
     if (data.status == "success")
         alert(document.getElementById("fff:stateSelected"));  
}

Upvotes: 7

Related Questions