Does the "onevent" option get disregarded for jsf.ajax.request in JSF

In my attempt to develop an interactive chat web application using Java EE 7, I am specifically utilizing JSF 2.2 with ajax.

The concept involves having a slow pending asynchronous ajax request waiting on the server for each unique client. When a new message is received by the server, all pending requests are triggered, causing messages to be displayed in all clients. Once the requests are completed, new ones are sent out by the clients. If no message arrives within 30 seconds, the request is returned for submission of a new one before the previous request times out.

I have managed to implement this functionality as shown below:

index.xhtml:

<?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:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">

    <h:head>
        <title>async jsf app</title>
        <h:outputScript library="js" name="resendscript.js" />
    </h:head>
    <h:body> 

        async jsf app
        <h:form id="jsfappform">
            say something: 
            <h:inputText id="newmsg" value="#{jsfAsync.newMessage}" />
            <h:commandButton id="sendbut" value="say" action="#{jsfAsync.say}" />
            <br /><br />
            Messages:
            <br /><br />
            <h:outputText id="msgs" value="#{jsfAsync.msgs}" escape="false">
                <h:outputScript>resendRequest()</h:outputScript>
            </h:outputText>            
            <h:commandButton id="reloadbut" value="" action="#{jsfAsync.resend}" style="visibility: hidden">
                <f:ajax execute="@this" render="msgs" onevent="handleAjax" onerror="handleError" /> 
            </h:commandButton>
            <h:commandButton id="clearbut" value="clear" action="#{jsfAsync.clear}" />
            <h:outputScript>resendRequest()</h:outputScript>
        </h:form>
    </h:body>
</html>

resendscript.js:

function handleAjax(data) 
{
    var status = data.status;
    switch(status) 
    {
        case "success": resendRequest();
                        break;
    }
}

function handleError(data) { }

function resendRequest() 
{
    document.getElementById("jsfappform:reloadbut").click();
} 

backing bean JsfAsync.java:

package jsfasync;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;

@ManagedBean
@ApplicationScoped
public class JsfAsync 
{
    private final List<String> messages;
    private final Object wakeup;

    public JsfAsync() 
    {
        wakeup = new Object();
        messages = new ArrayList<String>(); 
    }

    public void setNewMessage(String msg)
    {
        synchronized(messages)  {  messages.add(msg); }            
    }

    public void say()
    {  
        synchronized(wakeup)  {  wakeup.notifyAll();  }
    }

    public void resend()
    {         
        try { 
          synchronized(wakeup)  {  wakeup.wait(30000);  }
        } catch (Exception e) { }    
    }

    public void clear()
    {
        synchronized(messages)  {  messages.clear();  }
        say();
    }

    public String getNewMessage() {  return ""; }

    public String getMsgs()
    {
        StringBuilder msgs = new StringBuilder();
        synchronized(messages)
        {
            for (String m : messages)
            {
                msgs.append(m);
                msgs.append("<br />");
            }        
            return msgs.toString();
        }
    }
}

My intention is to update the body of the resendRequest() javascript function with the ajax request API in the following manner:

jsf.ajax.request('jsfappform:reloadbut', null, 
                 {'javax.faces.behavior.event': 'action', 
                  'execute': 'jsfappform:reloadbut', 
                  'render': 'jsfappform:msgs', 
                  'onevent': 'handleAjax',
                  'onerror': 'handleError'});

However, it seems that despite successfully performing the ajax request call, the onevent parameter was disregarded and the event handler did not execute upon completion of the request. Do you have any advice on how to address this issue?

Answer №1

To find clues, take a look at the generated HTML source of

<h:commandButton id="reloadbut">
. You'll notice that JSF has created it with 'onevent': handleAjax, using a function reference instead of a string.

Here's how to correct it:

jsf.ajax.request('jsfappform:reloadbut', null, 
                 {'javax.faces.behavior.event': 'action', 
                  'execute': 'jsfappform:reloadbut', 
                  'render': 'jsfappform:msgs',
                  'onevent': handleAjax,
                  'onerror': handleError});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing a button's value on click using PhoneGap

I've been working with phonegap and came across an issue with my buttons setup like this: <input id="my_button" type="button" onclick="my_function();"/> The goal is to capture the click event and change the button's value, my_function ( ...

Having difficulty accessing the 'makeCurrent' property of an undefined object in Angular mobile application

I have followed the steps outlined in the Angular mobile toolkit guide found at https://github.com/angular/mobile-toolkit/blob/master/guides/cli-setup.md My Node version is v4.4.3 NPM version is 2.15.1 The issue arises when I run the command $ ng serve, ...

JavaScript: An object containing a unified handler for all method invocations

Let me explain further. Math.add(2, 2) //4 Math.multiply(4, 9) //36 Whenever a method in the Math object is invoked, it triggers a central processor that interprets the function name to determine its action. Can an object execute a default function when ...

Refreshing an ajaxForm post content reload using ajax (version jQuery 1.4.2)

Why is this an issue when using jQuery 1.4.2 instead of 1.3.2? Here is the function in question: function prepare_logo_upload() { $("#logo-upload-form").ajaxForm({ //alert(responseText); success: ...

What are the steps to store and access state variables using session storage in a React application?

I am currently utilizing React version 18.2.0. In my application, I have a component called BodyComponent that stores the data retrieved from an API call in its state as results, along with some filter information in filters. The BodyComponent fetches the ...

Ajax htmlEditorExtender - Unidentified tag cleaner

Hello, I recently downloaded the newest version of the Ajax Toolkit from Microsoft and am in the process of setting up the sanitizer for the htmlEditorExtender. However, I keep encountering the following error when attempting to build the site: "Unrecog ...

jQuery: Eliminating Parent Elements

Currently, I am developing a small web application that allows users to create lists which are then formatted and emailed to them. However, I am facing difficulties in implementing a method that will allow users to delete list items without clearing the en ...

SVG tags are not functioning properly

Hello, I am new to working with SVG files. I have a set of icons created using SVG and I am attempting to use the <use> tag in order to display a specific part of an SVG file. However, I seem to be encountering some issues and I am unable to identi ...

Unbind a prepared statement in a node.js environment using SQL

Utilizing the node-mssql library (https://github.com/patriksimek/node-mssql) and encountered a problem when attempting to execute a second request, resulting in the following error: this.connection.pool.acquire(done); ^ TypeEr ...

What is the best way to hide only the rows in a table when it is clicked using JavaScript?

Is there a way to hide rows in these tables by clicking on the table head? I'm currently using bootstrap 5 so JQuery is not an option. <table class="table table-info table-bordered"> <thead id="tablea"> ...

Struggling to Personalize Kendo Calendar Month templates using Knockout Kendo JS Binding

I have made modifications to the Kendo Calendar Month Template Resource which can be found Here without utilizing knockout-kendo.js. The official Kendo Reference is available Here. The issue arises when I implement the following code in knockout-kendo.js ...

Show identical modal form for various database entities

I have numerous entities that adhere to the IEntity interface (in reality, I have around 10 entities). public interface IEntity { short Id { get; set; } string Name { get; set; } } public partial class Part: IEntity { } public partial class Locali ...

Creating interactive button groups with responsive design in a Material UI and ReactJS web application

Is it possible to make ButtonGroup Buttons responsive? I heard about an attribute called "Orientation" in material-ui's ButtonGroup, but I'm not sure how to use it with media queries for changing orientation based on the device width. I'm st ...

Angular's watch feature fails to trigger when the value is modified

My setup includes two sliders, one for brightness and the other for contrast. They are linked to a "brightness" model and a "contrast" model. These sliders are located within a tab interface, and I noticed that every time the tab was changed, the values we ...

Utilize the success() callback in JQuery Ajax when handling a response that is null

Within my website application, users have the ability to invite other users to participate in their projects. By entering an email address, a request is sent to the server via post method to check if the user exists. If the user is found, it will return th ...

Arranging numbers in JavaScript lists

empList = [ { "Account": "AAA - 0029", "Available": "$100" }, { "Account": "BBB- 0146", "Available": "200" }, { "Account": "AAA - 1812", "Available": "300"}, { "Account": "CCC- 2019", "Available": "400"}, { "Account" ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

Submitting Forms with XMLHttpRequest

I'm trying to utilize XMLHttpRequest in order to retrieve the response from a remote PHP file and showcase it on my webpage. The issue I'm facing is that the form's data isn't being submitted to the remote PHP page. Any suggestions on ...

When using `defineModel` in Vue, the returned value can be either an object or

defineModel() is a new feature introduced in Vue 3.4+. The official documentation provides the following example: const model = defineModel() model.value = 'hello' Initially, it appears that model is an object with a value property. However, th ...

javascript managing conflicts within jQuery scripts

I am facing an issue with the list of js files I have in my header.php on my website. The scripts are using jquery and ajax and include: <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/ ...