Invoking Wicket's JavaScript Function Within an AjaxRequestTarget

I am facing an issue with my web application built using Wicket framework. The problem arises when a part of my code runs within an AjaxRequestTarget for a long duration, and I need to display a busy indicator to inform the user about the ongoing process.

My attempt to use `target.appendJavascript("jsfunction()")` did not yield the desired result as it executes after the method's completion. How can I successfully implement this functionality?

Here is an example snippet of my code:


final ConfirmModal del_modal = new ConfirmModal("del-btn", "Are you sure?") {
    @Override
    public void onClickOK(AjaxRequestTarget target) {

        target.appendJavaScript("loadingFormFromTarget();");

        try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            Logger.getLogger(ListPricePlanPage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

UPDATE

A solution provided by martin-g worked well with AjaxLink, but my scenario is more complex. I have a ConfirmModal that extends ModalWindow with the following implementation:


public abstract class ConfirmModalPanel extends Panel {
    public ConfirmModalPanel(String id, String text) {
        super(id);

        add(new Label("text", text));

        AjaxLink ok = new AjaxLink("ok") {
            @Override
            public void onClick(AjaxRequestTarget target) {
                onClikOK(target);
            }

            @Override
            protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
                super.updateAjaxAttributes(attributes);
                attributes.getAjaxCallListeners().add(new AjaxCallListener().onBeforeSend("start();").onComplete("finish();"));
            }
        };

        add(ok);

        add(new AjaxLink("ko") {
            @Override
            public void onClick(AjaxRequestTarget target) {
                onClikKO(target);
            }
        });
    }

    abstract public void onClikOK(AjaxRequestTarget target);

    abstract public void onClikKO(AjaxRequestTarget target);
}

The functions "start()" and "finish()" are triggered correctly, however, the execution of the request inside the `onClickOK` method continues without showing the busy indicator.

Answer №1

The timing of onClickOk() is not ideal for this task. Content sent to the web response will only be displayed in the browser once the request has been completed.

In order to achieve the desired functionality, you should utilize AjaxCallListener#onBeforeSend() and onComplete(). These methods are executed on the client-side just before sending the request and after receiving the response.

For examples, please refer to this link and this link.

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

The inability to set MongoDB documents to automatically expire with TTL indexes

I'm currently facing a challenge in my Node.js application where I need to implement a TTL index on a date field within a MongoDB collection so that it automatically expires at a specified date. To achieve this, the application retrieves the current ...

Understanding the onStart and onStop lifecycle methods in Firebase for Android applications

Recently delving into Firebase for Android development, I find myself puzzled by the onStart and onStop methods. Why is it crucial to include code in the onStop method? And why must we remove the listener? @Override protected void onStop() { super.onS ...

Finding documents by name in Photoshop

When working with multiple open Photoshop files, the usual method of using getByName for layers or history states doesn't seem to work for documents. var srcDoc = app.Documents.getByName("Gwen_Stefani"); // no success Is this the correct ap ...

Create a Discord bot that will remain in a channel for a specific amount of time before automatically leaving, but will continue to

I'm currently working on a music bot that I want to automatically leave after a certain amount of time, unless 24/7 mode is enabled and the queue ends. The problem I'm facing is that when new audio starts playing, the bot still leaves after the s ...

Employing polyglot to communicate with a GRPC service and include a timestamp as a request parameter

When using the command line to call polyglot in order to query a GRPC service, I am facing an issue with passing a valid timestamp in the request object. The attribute for TimeStamp is named 'as_of'. Can anyone advise on what format a valid times ...

Efficiently transmitting WebSockets events/messages to multiple controllers in AngularJS

Incorporating AngularJs, I created a factory to manage a WebSocket connection effectively. Here is the code: .factory('WebSocketConnection', function () { var service = {}; service.callbacks = []; service.connect = func ...

The error message "TypeError list.map is not a function" indicates that

Could someone please explain why I am encountering the error 'list.map is not a function' in my code? I'm unsure why list.map isn't working as expected. https://i.sstatic.net/ah3ZL.png Below is the snippet of my code: singleProduct ...

`When is it appropriate to utilize dispatch within an action creator function?`

I have created two functions in my ActionCreator.js file. First: export const fetchAudioForVerification = ()=>{ return fetch(baseUrl+'audio',{ // Perform Get Request } .then(response=>response.json());} Second: export const handleAudio ...

Ways to remove the highlighting from a selected list item using CSS/Javascript

I have a problem with a list of images and keywords that act as selections for users. When a user clicks on a selection, it highlights the corresponding image using CSS shadow. However, I am trying to figure out how to deactivate this highlight later on, e ...

What should I do when the ng-click event doesn't open a new window

<p ng-click='window.location.href="{{data.url}}"''>{{data.name}}</p> Is there anything incorrect about this code snippet? I attempted using onclick as well, but encountered an error in the console. ...

Unable to display a cube using Three.js on a custom WebGL layer in Mapbox GL JS

Attempting to showcase the cube using this example: Add a 3D model. The example functions fine up to version 117 on three.js. However, starting from version 118, the cube disappears immediately after refreshing the page. After reviewing the changelog, it ...

Use Node-RED to fetch JSON or CSV data and store it in InfluxDB

Versions Node-RED v0.16.2 InfluxDB v1.2.2 Grafana v4.2.0 Ubuntu 16.04.2 I'm looking to access weather data from a local official weather station. The options available are in either csv or JSON format. I am attempting to retrieve the JSON feed us ...

Retrieve information and auto-fill text boxes based on the selected dropdown menu option

UPDATED QUESTION STATUS I'm currently working with Laravel 5.7 and VueJs 2.5.*. However, I am facing a challenge where I need to automatically populate form textboxes with data from the database when a dropdown option is selected. Despite my efforts ...

IE throwing an invalid argument error when making an AJAX request

I have a strange issue with my ajax request - it works perfectly fine in all browsers except for IE, specifically IE10! The error message I am encountering in the IE console is as follows: SCRIPT7002: XMLHttpRequest: Network Error 0x80070057, Invalid arg ...

What is the best way to populate a Set with an array of diverse objects that all inherit from the base object contained within the

Is there a way to populate a Set<SomeObject> with an array (Object[]) containing objects that extend the object in the Set? I have an array of objects and I want to convert it into a set of objects that are extensions of the objects in the array. He ...

Error encountered when trying to access the _id property in React Components using MongoDB and passing a Key: TypeError - Property _id is undefined

I've encountered an issue when trying to pass a field from MongoDB into a React Component. Here is the snippet of code I'm working with: import React from 'react'; import ReactDOM from 'react-dom'; import { Meteor } from &apo ...

What is the best way to access a variable from a different JavaScript file?

How can I access the 'name' value from a JavaScript file in an AngularJS application? Consider the following code snippet: var myApp = angular.module('myApp',[]); myApp.factory('UserService', function() { return { ...

I am unable to input just one numerical value into my function

I am encountering an issue with my function that calls another function. The problem arises when inputting single numbers in the prompt; I have to append a letter like (a1, a2, a3) for it to function correctly. The function "PrintSelectedToPDF" works smoo ...

Having trouble with a basic if-then condition

I'm trying to make a div expand and contract when it's clicked. Here's the code I've used: <div ng-click="disclaimer();" style="height:100px;width:100px;overflow:{{expand}}">Sample Text</div> Essentially, when the user cli ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...