DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Spring Boot: Cross-Origin AJAX HTTP Requests
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Memory Management in Couchbase’s Query Service
  • How to Build Slack App for Audit Requests

Trending

  • Designing a Java Connector for Software Integrations
  • Mastering Advanced Aggregations in Spark SQL
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • Memory Leak Due to Time-Taking finalize() Method
  1. DZone
  2. Coding
  3. Frameworks
  4. JSF 2.3 — Execute an AJAX Request Using Globally Scoped Functions

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.

By 
Anghel Leonard user avatar
Anghel Leonard
DZone Core CORE ·
Jun. 27, 16 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
13.3K Views

Join the DZone community and get the full member experience.

Join For Free
Sometimes, it may be useful to encapsulate the AJAX requests in JavaScript functions placed in the JavaScript global scope in such way that we can simply call them by name, without arguments, or with arguments that represent the data that should be passed to the server‐side via the encapsulated AJAX request. Obviously the jsf.ajax.request() and mojarra.ab() functions donʹt allow us to accomplish that, but as you will see, JSF 2.3 (and OmniFaces) will call the jsf.ajax.request() from a JavaScript global scoped function that can be easily called by its name.


Letʹ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>


Note that the sendFeedback() function should be defined as a global scoped JavaScript function capable of firing a JSF AJAX request. The username and feedback should be added as parameters of the AJAX request.


JSF 2.3 comes with a handy new component named CommandScript (starting with JSF 2.3.0-m06) which is capable to solve this kind of tasks. This component be used by the page authors via the <h:commandScript/> tag. This component extends the javax.faces.component.UICommand (<h:commandXxx/>) which means that it inherits the major features of JSF commands, like action, actionListener, immediate, etc. Moreover, this component also supports nesting of <f:param/>, <f:actionListener/>, and <f:setPropertyActionListener/>, exactly as in <h:commandXxx/>.


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>


It is important to notice that this is just a simple JSF AJAX request, so when we call the sendFeedback() function, we will fire an ʺemptyʺ JSF AJAX request. Obviously, we are interested to control the values of the execute and render attributes. This is very simple, because <h:commandScript/> supports the execute and render attributes exactly as <f:ajax/>, so we can do this:
<h:form>
 <h:commandScript name="sendFeedback" execute="@form" render=":savedId"/>
</h:form>


Now, the generated code becomes:
<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>


With just a snap of a finger we can add the action:
<h:form>
<h:commandScript name="sendFeedback" execute="@form"
                 render=":savedId" action="#{feedbackBean.send()}"/>
</h:form>


So far, so good! If you donʹt have extra information to pass to the server‐side, or it is collected from the form (e.g. <h:inputText/>), then this should be enough. But, in our case we have extra information to pass and this information comes through plain HTML code, so we have to find a solution for adding this information into the JSF AJAX request. Thanks to the <h:commandScript/> the generated function also supports a JavaScript object as an argument which will then end up in the HTTP request parameter map (donʹt forget about <f:param/>). In order to pass an object to the generated function, we need to wrap its call into a global JavaScript function, as below:
<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>


On the server‐side, the passed information can be easily extracted via the OmniFaces  Faces#getRequestParameter() utility method:
String user = Faces.getRequestParameter("user"); // user
String feedback = Faces.getRequestParameter("feedback"); // feedback


Or, we can use the JSF pure solution:
Map<String, String> params = FacesContext.getCurrentInstance().
                                  getExternalContext().getRequestParameterMap();

String user = params.get("user"); // user
String feedback = params.get("feedback"); // feedback


The complete application is available here. The application was tested under Payara 4 with JSF 2.3.0-m06.
AJAX Requests

Published at DZone with permission of Anghel Leonard, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot: Cross-Origin AJAX HTTP Requests
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Memory Management in Couchbase’s Query Service
  • How to Build Slack App for Audit Requests

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!