Invoke Wicket 6 code using Javascript and retrieve the result

I successfully implemented a way to call my Wicket 6 Java code from JavaScript using option A, as demonstrated in this example:

However, I am now facing the challenge of finding examples for returning data from the Java side back to JavaScript. The generated JavaScript callback function does not include a return statement. How can I accomplish this?

In clarification, I am not attempting to set an attribute in Java. Calling Wicket from JavaScript is not the issue at hand. My goal is to return a JSON object from Wicket to the browser as a result of an Ajax request.

Finding inspiration from martin-g's examples, I developed a functional implementation...

Java

public class MyAjaxBehaviour extends AbstractDefaultAjaxBehavior {

    @Override
    protected void onComponentTag(ComponentTag tag) {
        super.onComponentTag(tag);
        tag.put("aprachatcallbackurl", getCallbackUrl());
    }

    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
        super.updateAjaxAttributes(attributes);
        attributes.setDataType("json");
        attributes.setWicketAjaxResponse(false);
    }

    @Override
    protected void respond(AjaxRequestTarget target) {
        getComponent().getRequestCycle().replaceAllRequestHandlers(
            new TextRequestHandler("application/json", "UTF-8", "{...JSON GOES HERE...}));
    }
}

JavaScript

var mySuccessCallback = function(param1, param2, data, statusText) {
    // Data contains the parsed JSON object from MyAjaxBehaviour.respond(...)
    ...
}

var myFailureCallback = function() {
    ...
}

Wicket.Ajax.get({
    "u": callbackUrl,
    "dt": "json",
    "wr": false,
    "sh": [mySuccessCallback],
    "fh": [myFailureCallback]
});

The main issue lies in the fact that the Wicket 7 Reference incorrectly advises to use "wr" instead of "dt" in the JavaScript call. :)

Answer №1

I believe there is a simpler way to accomplish this task!

To utilize the Wicket Ajax API, you only need to use: Wicket.Ajax.ajax({...}). On the server side, all you have to do is save the callback URL, which can be done by storing it globally in the window object or within HTML element attributes like data-the-url.

public class CallFromJavascriptBehavior extends AbstractDefaultAjaxBehavior {
   @Override
   protected void respond(AjaxRequestTarget target) {
      final StringValue parameterValue = RequestCycle.get().getRequest().getQueryParameters().getParameterValue("yourName");
      System.out.println(String.format("Hello %s", parameterValue.toString()));

      // Write something to the WebResponse and then access it in the JS success handler. Refer below for details
   }

   @Override
   public void onComponenntTag(ComponenntTag tag, Component component) {
       super.onComponenntTag(tag, component);
       tag.put("data-the-url", getCallbackUrl());
   }
}

In your JavaScript code, you can then proceed with:

var callbackUrl = jQuery("#theElementId").data("the-url");
Wicket.Ajax.get({"u": callbackUrl, "sh":[successHandler], "fh": [failureHandler] });

The successHandler and failureHandler functions can either be defined inline as function(...) {} or externally.

For further information and documentation, kindly visit:

You can also explore a detailed example in a blog article at

Answer №2

If you want to utilize a Resource and attach it for use with your preferred Ajax technique, you can easily do so.

Here's an illustration:

public class MyResource extends AbstractResource
    @Override
    protected ResourceResponse newResourceResponse( Attributes attributes )
    {

        ResourceResponse resourceResponse = new ResourceResponse();
        resourceResponse.setContentType( "text/json" );
        resourceResponse.setTextEncoding( "utf-8" );

        HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();

        try
        {
            this.json = IOUtils.toString( request.getInputStream() );
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }

        resourceResponse.setWriteCallback( new WriteCallback()
        {
            @Override
            public void writeData( Attributes attributes ) throws IOException
            {
                OutputStream outputStream = attributes.getResponse().getOutputStream();
                Writer writer = new OutputStreamWriter( outputStream );


                writer.write( MyResource.this.json );
                writer.close();
            }
        } );

        return resourceResponse;
    }

(Extracted from my earlier response available at )

To implement the mounting process, check out the following 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

Passing the output of a function as an argument to another function within the same HTTP post request

I have a situation where I am working with two subparts in my app.post. The first part involves returning a string called customToken which I need to pass as a parameter into the second part of the process. I'm struggling with identifying where I m ...

Storing JSON arrays in MongoDB becomes chaotic when using the .save() function from Mongoose

I'm faced with the challenge of storing a lengthy JSON array in a free MongoDB database collection. To achieve this, I establish a connection to my database using mongoose and then utilize a for loop to iterate through each JSON object in the array. ...

Error message encountered in Android Studio: Class duplication detected

Currently, I am learning Android development. I have created 2 layout files and 2 Java files. However, when I try to connect them, I encounter an error message stating "checkDebugDuplicateClasses - duplicate class found". I have thoroughly checked my fil ...

Storing Objects in MongoDB using Node.js

I am working on an application where I need to store an object for later execution of functions. This object essentially holds the data of a cron job. var cronJobObject = schedule.scheduleJob(new Date(2018, 0, 19, 15, 15, 0), function() { console.log( ...

Using a boolean checkbox with Spring MVC and implementing ajax

On my HTML page, I have a boolean checkbox that looks like this: <input type="checkbox" id="pnrCheckbox" name="includesPnr" value="true"/> <!-- This field is generated by Spring as a workaround for something --> <input type="hidden" name="_ ...

Having issues executing TestNG project through command prompt commands

I've been struggling with a persistent issue for several days now, and despite scouring Google for answers, I haven't found a solution yet. My problem arises when trying to run my TestNG project tests through the CMD. Initially, running the proj ...

What is the best method for bringing in string values (a, b, c) to create 3D shapes in three.js

Currently, as a javascript three.js beginner, I am tackling a project that involves importing string values (x, y, z) into a three.js file in order to generate cubes or spheres with those values. These values are sourced from a json file and are converted ...

Modifying the input's value dynamically alters the selection choices in Vuetify

Choose the First option Fpo, when you select the first item, the first object in the list is assigned to the variable test. I have used test.name as a model for that input field. Strangely, when I try to modify the input field, the select option also chang ...

How can I uniquely combine a code with an existing CSS class and make modifications to it?

I am using ngx-skeleton-loader and I would like to change the color, but I am facing some difficulties. Here is an image that illustrates the issue. When looking at the developer tools, you can see the styles action in the styles action bar. .loader ...

What is the best way to generate a consistent and unique identifier in either Javascript or PHP?

I attempted to search for a solution without success, so I apologize if this has already been discussed. Currently, I am in need of an ID or GUID that can uniquely identify a user's machine or the user without requiring them to log in. This ID should ...

Utilizing the power of HTML datalist and *ngFor to present one value while sending another

I am currently working on a project that involves creating an autocomplete text box using the <datalist> tag with *ngFor functionality. However, the code I am using is showing both the value declared with [value] and the input between the <option& ...

Ensure that both the top row and leftmost column are fixed in a vertical header using JQuery DataTable

Check out the implementation of vertical header flow in Datatables by visiting: https://jsfiddle.net/2unr54zc/ While I have successfully fixed the columns on horizontal scroll, I'm facing difficulty in fixing the first two rows when vertically scroll ...

Utilize the power of Elasticsearch.js along with Bluebird for enhanced performance

Recently delving into node.js, I've been exploring the powerful capabilities of the bluebird promise framework. One of my current challenges involves integrating it with the elasticsearch javascript driver. After some experimentation, I was able to su ...

Conflicting jQuery slide effects and jQuery UI positioning causing issues

As you hover over an element, the position function adjusts its left attribute to the correct value. However, when you move the mouse away, it resets back to 0, causing the element to appear below the first one in the list. This issue is noticeable when y ...

Is there a way to distinguish the HTML Elements from the CSS elements and retrieve them individually?

I am working on achieving a specific task and this JS fiddle represents one part of it. Check out the JS Fiddle here alert($("#content")[0].outerHTML); When executed, this code returns the following DOM structure: <div id="content"> <div ...

What is the best way to concentrate on necessary or incorrect fields?

In the event that users scroll down and miss some of the required fields in a lengthy form, they may not see error messages when clicking the Save button to submit the form data. Is it possible to implement an on focus method that automatically directs the ...

utilizing Nuxt code in Elixir/Phoenix

Overview In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy. Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix. ...

The Contact.php page has the ability to send emails, however, the content of the

I have recently added a contact form to my website using a template. Although I am able to send and receive email messages successfully, I am facing an issue where the actual message content entered by users is not being received in my Inbox. Here is a sc ...

Attempting to showcase the information in my customized SharePoint Online list through a Web Part Page utilizing AngularJS

<script> //AngularJS Code goes here var appVar = angular.module('listApp', ['ngRoute']); appVar.controller("controller1", function($scope){}); function FetchEmployeeData($scope, EmployeeList){ var reque ...

Does an invisible property value exist?

Instead of: if ( ! $('#XX').is(':visible) ) Is there a property named invisible? I tested that one out, but it seems to not work. Appreciate the help! ...