JSF 2.3 — Execute an AJAX Request Using Globally Scoped Functions
In this article, using JSF 2.3 we'll go over how to generate a JavaScript function in the global JavaScript scope which allows the end user to execute a JSF AJAX request by just a function call in the JavaScript context.
Join the DZone community and get the full member experience.
Join For FreeLetʹs take a look at this simple HTML code:
<h5>Your Feedback About JSF 2.3: </h5>
<div>
Your Name: <input id="userId" type="text"/>
<p id="feedbackId" contenteditable="true">type your feedback here</p>
</div>
<br/>
<button onclick="sendFeedback();">Send Feedback</button>
In addition, the foundation of CommandScript consists of the fact that it can generate a JavaScript function in the global JavaScript scope. Via this function call, the end‐user can execute JSF AJAX requests. There are two requirements for this component:
- The name attribute is mandatory, and it indicates the name of the generated JavaScript function (you can define namespaced function name also by using a dot, ".", inside the function name).
- The <h:commandScript/> must be nested in a <h:form/>.
For example, the simplest way to use <h:commandScript/>, is listed below:
<h:form>
<h:commandScript name="sendFeedback"/>
</h:form>
This example is correct, but it doesnʹt do much! Basically, it generates in page a snippet of code as below:
<span id="j_idt5:j_idt6">
<script type="text/javascript">
var sendFeedback=function(o){
var o=(typeof o==='object')&&o?o:{};
mojarra.ab('j_idt5:j_idt6',null,'action',0,0,{'params':o})
}
</script>
</span>
<h:form>
<h:commandScript name="sendFeedback" execute="@form" render=":savedId"/>
</h:form>
<span id="j_idt5:j_idt6">
<script type="text/javascript">
var sendFeedback=function(o){
var o=(typeof o==='object')&&o?o:{};
mojarra.ab('j_idt5:j_idt6',null,'action','@form','savedId',{'params':o})
}
</script>
</span>
<h:form>
<h:commandScript name="sendFeedback" execute="@form"
render=":savedId" action="#{feedbackBean.send()}"/>
</h:form>
<h:outputScript>
function sendFeedbackWrapper(){
sendFeedback({user: document.getElementById("userId").value,
feedback: document.getElementById("feedbackId").innerHTML });
}
</h:outputScript>
And, modify the button as:
<button onclick="sendFeedbackWrapper();">Send Feedback</button>
String user = Faces.getRequestParameter("user"); // user
String feedback = Faces.getRequestParameter("feedback"); // feedback
Map<String, String> params = FacesContext.getCurrentInstance().
getExternalContext().getRequestParameterMap();
String user = params.get("user"); // user
String feedback = params.get("feedback"); // feedback
Published at DZone with permission of Anghel Leonard, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments