I am attempting to retrieve JSON data in JavaScript but am seeing a null response in the action class

Having an issue with JSON data being sent through AJAX from the client side. The data is showing as null inside my action class.

Here is the JSON string:

{"data":[{"id":"","col":1,"row":1,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":2,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":3,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":4,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":6,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":5,"size_x":1,"size_y":1}
        ]
}

AJAX setup:

var seats = {"data" : positions};

    var seatPosition = JSON.stringify(seats);

    console.log(seatPosition);  

    $.ajax({
        url: 'retrieve-seat',
        data: seatPosition,
        dataType: 'json',
        contentType: 'application/json',
        type: 'POST',
        async: true,
        success: function (data) {
        alert("success");

Configuring in struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

<constant name="struts.devMode" value="true" />
<constant name="struts.action.extension" value="," />
<constant name="struts.enable.SlashesInActionNames" value="true" />
<constant name="struts.custom.i18n.resources" value="global" />

<package name="default" namespace="/"
    extends="json-default,struts-default">

    <action name="retrieve-seat" class="com.pointwest.apex.actions.ReadPositionAction">
        <result name="SUCCESS" type="json"/>
    </action>

</package>

</struts>

Action class implementation:

public class ReadPositionAction extends ActionSupport {

private List<Seat> data;


public List<Seat> getData() {
     System.out.println("Getter Call");
    return data;
}

public void setData(List<Seat> data) {
     System.out.println("Setter Call");
    this.data = data;
}

@Override
public String execute() {
    System.out.println("action");
    try {
        System.out.println(data);


        System.out.println("Execute Method");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "SUCCESS";
}

}

The JSON format appears to be correct based on the console log. Any assistance would be greatly appreciated. Thank you!

Answer №1

If you are looking to generate JSON (Action -> JSP), simply use the json result.

If you need to parse JSON data (JSP -> Action), incorporating the Json Interceptor into your stack is essential.

According to the provided documentation:

Accepting JSON

Your actions can receive incoming JSON when they belong to a package that employs the json interceptor, or by adding a reference to it like this:

@InterceptorRef(value="json")

It's important to remember that the json-default package internally extends the struts-default, eliminating the need to extend both separately.

The configuration should look like this:

<package name="default" namespace="/" extends="json-default">

    <interceptor-stack name="jsonFromJspStack">
        <interceptor-ref name="defaultStack"/>
        <interceptor-ref name="json" />
    </interceptor-stack>


    <action name="retrieve-seat" class="com.pointwest.apex.actions.ReadPositionAction">
        <interceptor-ref name="jsonFromJspStack"/>
        <result name="SUCCESS" type="json"/>
    </action>

</package>

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

An issue has been encountered in NodeJS with a route that begins with a percent sign causing an error

I have a NodeJS server set up with the following backend configuration: app.use(express.static(__dirname)) app.get('/', function(req, res){ res.send('main page here') }); app.get('/*', function(req, res){ res.send(&apos ...

Loading information in a directive by utilizing promises in a service with AngularJS

Can anyone lend a hand? I've been struggling to solve this issue. I created a directive (see below) to display a pre-written ul-list on a page using html data fetched asynchronously from a database server. Both the Directive and The Service are funct ...

What type of technology is typically utilized in creating functional platforms such as goDaddy, wix, and other web design websites?

I am currently working on a web development project that aims to allow users to edit webpages without needing any coding knowledge. Users with authorization will be able to modify not only the text but also various HTML tags on the page, similar to platfor ...

Harnessing the power of Shopify's Predictive Search API

I am currently working on implementing a custom solution using the predictive search API for when a product is out of stock. Our goal is to display an alternate product that we have chosen, rather than relying on automated recommendations. We have tagged a ...

Create a new attribute within the ng-model object once it has been updated through ng-repeat

I am trying to figure out how to add a "discountRate" property to an ng-model object after it has been changed within an ng-repeat block. Check out this example for more information Another example can be found here Although the ng-model is updated as e ...

What is the best way to run a function within an if statement without duplicating code if the condition is false?

When working with relay mutation code, I find it necessary to reload the store in order for it to sync with the database. This is because if the text being added is the same as previously added text, the relay store throws an error called flattenChildren.. ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

Regex: Enabling commas in the name of an Excel file

My JavaScript code is set up to extract data from an excel file. As a first step, I define a regular expression and assign it to a variable named regex var regex = /^([a-zA-Z0-9\s_!()\\.\-:])+(.xls|.xlsx)$/; Following this, there is s ...

Issues with form rendering in a Vue.js component

I have recently started learning vue.js and I'm trying to create a basic form using the materializecss framework within a component. The form requires this jQuery snippet to function: $(document).ready(function() { M.updateTextFields(); }); ...

Tips for transforming an input into a format that is readable by the program

Currently, I am tackling an assignment on the client and server topic. In my project, I have implemented a class named VehileRequest.java. This class takes three variables (year, make, model) from Client.java, passes them to Server.java, and then retrieves ...

How come the useState function remains undefined, even when initialized with a default value?

I attempted to set an empty array as the default value for a state using the useState hook in React. However, when I try to check the type of testing with console.log(Array.isArray(testing)); or simply log testing, it always displays undefined regardless o ...

npm installs a multitude of dependencies

Recently, I purchased an HTML template that includes various plugins stored in a directory named bower_components, along with a package.js file. While trying to add a new package that caught my interest, I opted to utilize npm for the task. Upon entering ...

Combining the total of numerous inputs that are multiplied by a specific value all at once

Hey, I've been working on a project with a table and an input field with costs using jQuery. You can check out This Fiddle for reference. $( ".total" ).change(function() { let i = 1; var input001 = document.getElementsByName(i)[0]; var ...

Puppeteer: Easier method for managing new pages opened by clicking a[target="_blank"]; pause for loading and incorporate timeout controls

Overview I'm seeking a more streamlined approach to managing link clicks that open new pages (such as target="_blank" anchor tags). By "handle," I mean: fetch the new page object wait for the new tab to load (with specified timeout) Steps to r ...

The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json. After examining the JSON format using console.log(JSON.stri ...

An Android error message is displaying: "JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject"

My introduction to JSON is quite recent, and I've been watching Youtube videos for guidance on handling the error described in this link: question. Despite my efforts, I'm still confused as to why I keep encountering the same error. Here's ...

How to transfer a C library callback to a NodeJS EventEmitter with the help of node-addon-api

In the process of developing a node module that integrates Alex Diner's cross-platform gamepad code using the Node-Addon-API, I encountered an interesting challenge. Making the module function as an EventEmitter and exposing callback functions throug ...

Having trouble with the Three.js OBJ loader in CodePen?

Currently, I am experiencing a challenge with loading an OBJ file on Three.js. Oddly enough, the functionality seems to be working perfectly fine when I deploy the files on my server as demonstrated here: However, when attempting to run it on Codepen, I e ...

How can one generate an array containing all attributes found in the HTML of a website?

I have a project idea where I want to be able to input a hyperlink address and then get a list of attribute contents as the output. For instance, if I input a Netflix genre hyperlink for Adventure Movies, I'd like to receive a list with all the movie ...

css failing to load properly following javascript redirection

Upon clicking the button labeled id=cancel, the user will be directed to index.php. $('#cancel').click(function() { if(changes > 0){ $('#dialog-confirm').dialog('open'); }else{ window.location.href = ". ...