Enot
Enot

Reputation: 830

Handles data response from JSF Ajax in Javascript

I have the follow Managed Bean class:

  import javax.faces.bean.ManagedBean;
  import javax.faces.bean.SessionScoped;

  import java.io.Serializable;

  @ManagedBean
  @SessionScoped
  public class HelloBean implements Serializable {

private static final long serialVersionUID = 1L;

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSayWelcome(){
    //check if null?
    if("".equals(name) || name ==null){
        return "";
    }else{
        return "Ajax message : Welcome " + name;
    }
   }

}

And this the JSF file:

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:f="http://java.sun.com/jsf/core"      
  xmlns:h="http://java.sun.com/jsf/html">

<h:body>
    <h3>JSF 2.0 + Ajax Hello World Example</h3>

    <h:form>

        <h:inputText id="name" value="#{helloBean.name}"></h:inputText>
        <h:commandButton value="Welcome Me">
             <f:ajax execute="name" onevent="example" render="output" />
        </h:commandButton>

        <h2><h:outputText id="output" value="#{helloBean.sayWelcome}" /></h2>

    </h:form>

</h:body>

And this javascript function that I call when ajax response has been completed that receive a data parameter:

function ejemplo(data){
        $('#tablaEjemplo').append('<table><thead><tr><th>User</th></tr></thead>'+
                                   '<tbody><tr><td>'+data.name+'</td></tr></tbody>           </table>');
        }

My pretensions are when the ajax response is success, print a table with the username of the manage bean that I inserted in the input text but I don't know how to access the parameter (the data.name obviously doesn't work) for print, I don't know really if f:ajax is returning something or I have to set up in some place (I guess in the manage bean...) something like format JSON data to retrieve and can access in my function, no?. Any ideas?

Upvotes: 0

Views: 3539

Answers (1)

Alexandre Lavoie
Alexandre Lavoie

Reputation: 8771

If you want to show the name, why not only adding it to the ajax rendered part like this :

<h:commandButton value="Welcome Me">
    <f:ajax render="output" />
</h:commandButton>

<h2><h:outputText id="output" value="#{helloBean.sayWelcome} #{helloBean.name}" /></h2>

If the name is null it will only not show at all.

Upvotes: 1

Related Questions