Using Ajax to send a JSON object containing two arrays to a servlet, then parsing it in a Java servlet without the use

When sending data to a servlet, I utilize an Ajax POST call to send a JSON object containing two arrays. In the servlet class in Java, I need to read this data sent in two lists or arrays. I am avoiding the use of jQuery for the Ajax call and am not very familiar with JSON. Although I found some code on Stack Overflow to help with this task, I am unsure if there is an issue with sending or parsing the data.

Below is the JavaScript method for making the Ajax call, with "cback" representing the callback function, "method" as "POST," and "url" as the servlet URL:

function makeCall(method, url, from, to, cback) {
    var req = new XMLHttpRequest(); 
    req.onreadystatechange = function() {
        cback(req)
    }; 
    req.open(method, url);
  
    var obj = {};
    obj["from"] = from;
    obj["to"] = to;
    var data = JSON.stringify(obj);
    req.send(data);
    

}

Continuing, here is the doPost method within the servlet controller specified by the URL. The issue arises when attempting to retrieve the data using getParameter, as the strings "json1" and "json2" end up being null:

       
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            
       //...
            
       String json1 = request.getParameter("from");
       String json2 = request.getParameter("to");

       Gson gson = new Gson();
       ArrayList<Double> listFrom = gson.fromJson(json1,
                new TypeToken<ArrayList<Categoria>>() {}.getType());

       ArrayList<Double> listTo = gson.fromJson(json2,
                new TypeToken<ArrayList<Double>>() {}.getType());
                
      //...
}

Answer №1

Ensure your AJAX request is sending JSON data while your servlet is expecting form data containing JSON. To meet the server's expectations, encode each array as JSON and send them as form data.

function initiateRequest(method, endpoint, sender, recipient, callback) {
    var request = new XMLHttpRequest(); 
    request.onreadystatechange = function() {
        callback(request)
    }; 
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    request.open(method, url);
  
    var parameters = new URLSearchParams({to: JSON.stringify(recipient), from: JSON.stringify(sender)});
    request.send(parameters.toString());            
}

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

Tips for inserting and saving JSON data into an SQL server with Node.js

Attempting to execute a query in SQL Server using Windows authentication with Node.js. I have successfully implemented the GET request for select queries, but now I am facing issues with the POST request for insert queries. The problem arises when trying t ...

Leveraging API data within React: A step-by-step guide

I have a React application where I am making API calls. To manage these calls, I created a separate file called dataService.js to contain all the functions for interacting with the API. However, when trying to log the data in my component, I am getting a ...

Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface. However, I encount ...

Calling functions in AngularJS/HTML can help you execute specific

Just started with angularjs and facing some major issues haha... I have something that seems to be working fine, but I can't figure out what's wrong with this code... can someone please help me? Here it is: Basically, the scope.create function ...

Invoke a fresh constructor within a $get method in Angular's provider

I'm encountering an issue where I am attempting to utilize a function as a constructor inside the `.provider`, but I'm unable to instantiate a new constructor when it's within the `$get`. Here is my provider setup - this.$get = $get; ...

Issue: the size of the requested entity is too large

Encountering an error message while using express: Error: request entity too large at module.exports (/Users/michaeljames/Documents/Projects/Proj/mean/node_modules/express/node_modules/connect/node_modules/raw-body/index.js:16:15) at json (/Users/ ...

The behavior of a fixed position in Flexbox varies when comparing Chrome to Safari and Firefox

In Chrome, the following code works as expected, with the list element positioning itself at the very left of the .PageContainer when scrolling down. However, in Safari and Firefox, the list element positions itself just after the logo. Are there any CSS r ...

Challenges with finding a particular button in a popup window - Selenium

I'm struggling to click on a button within a modal dialog. I've searched online for solutions, but either I'm confusing myself (a high possibility) or the suggested fixes aren't working in my specific scenario. Here's the situatio ...

Pressing a button triggers the highlighting of a tab in HTML through the use of Javascript

In the corner of my webpage, I have three tabs: info, question, order. When I click on one tab header, only that tab should highlight. The info section includes two buttons that link to the question and order tabs. When these buttons are pressed, the respe ...

Ensure the user is authenticated following an asynchronous request

Currently, I am working with Cake PHP 2.4 and encountering an issue where my AJAX requests fail to work after the session has been idle for a while or if the user logs out in another tab. This is due to the fact that the user is already logged out when the ...

Java array cloning with clone()

Currently, I am experimenting with my copy constructor: protected int forca; protected Spell []feitico; public Picareta(final Picareta rValue) { super((Ferramenta)rValue); this.forca=rValue.forca; this.feitico=rValue.feitico. ...

The functionality of Dnd-kit nested is functioning properly, however, one specific component is unfortunately

Currently, I am dealing with a two-dimensional array that results in two nested dnd-kit drag and drop fields. The nested dnd functions correctly; however, the first one sorts items when moved without any animations (even when moving my div). Below is the ...

Encountered an issue when attempting to establish a connection with the REST

I am encountering an issue with connecting to a web service deployed on an Apache server using Jersey. The error message I receive is: Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' ...

Tips for capturing a jQuery trigger in traditional JavaScript

I am trying to trigger an event using jQuery and I want to bind to it in a non-jQuery script. It appears that while I can bind to the event in jQuery using on, I am unable to do so with addEventListener. Check out this jsFiddle for a demonstration: http: ...

Exploring the intricacies of handling exceptions in the service layer with Spring and Angular JS

Our team of developers is currently working on an application that utilizes jasper-reports 6.2.0, spring-mvc 3.2.14, java-ee-7, tomcat 8, and angularjs in the front-end. All our rest requests are made using ajax. The application is designed to receive JSO ...

Steps for launching Angular 5 application using Node.js server

I have developed an Angular 5 application that retrieves data from a node.js server. I successfully deployed the application to my web server hosted by FastComet, which supports node.js, but unfortunately, the server does not seem to be functioning properl ...

Obtaining the MasterTableView Edit Form within a Radgrid to acquire a reference to a textbox

Can anyone help me with two things, please? I am struggling to access the currently edited existing row in the Radgrid and also the index of the Edit form when attempting to add a new record to the table. function OnClientSelectedIndexChanged(sen ...

ReactJs throws an error of "Uncaught SyntaxError: Unexpected token '<' while utilizing the map() function in ReactJs that produces JSX (specifically MaterialUi-icons) within an array

In the file constant.js, I have defined object names and icons as keys. The key icon contains the icon component from @mui/icons-material, but when I attempt to retrieve the value from the icon, I encounter an error. Uncaught SyntaxError: Unexpected toke ...

In Laravel, pagination displays tables that contain some values from the paginate() function, but not all values

Currently testing my API in Postman, it successfully returns values but not pagination data. http://localhost/api/v1/projects-data //This is api Here is the image of the data that is returned to Postman: I have placed the route code in api.php Route::ge ...

Common Issues with Python JSON File Loading

I keep running into an issue while attempting to load a file into a variable. The error message json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) keeps popping up in relation to the line whitelist = json.load(f). Can anyone spot what ...