What is the best way to send an array from a JavaScript function on a JSP page to the controller class?

After implementing a JavaScript button action to push all checked elements on a jsp page into an array, the next step is passing this array to the controller class for further manipulation. Specifically, I need to be able to delete elements from that array within the controller function. How can this be achieved? The necessary components for achieving this task include the JavaScript function, JSP form, and controller class functions listed below.

<script type="text/javascript">
function selected(){
var all_checked = document.querySelectorAll('input[name=checkbox]:checked');

var selectedIds = [];

for(var x = 0, l = all_checked.length; x < l;  x++)
{
selectedIds.push(all_checked[x].value);
}

return selectedIds; 
}

</script>

> The selectedIds variable contains the checked items in the JSP page.
<form:form method="post" action="createnewstory/${userstoryId} }" modelAttribute="selectedIds" modelAttribute="fulluserstory">
... (remaining HTML code)

@RequestMapping(value="/createnewstory",method=RequestMethod.POST)
public String createNewStory(Map<String,Object> map,@ModelAttribute("fulluserstory") Fulluserstory fulluserstory,@RequestParam String actionButton,HttpServletRequest request){
if (actionButton.equals("Delete Selected")){
int [] checkedlist={73,74};
 for(int i=0;i<checkedlist.length;i++){
 int userstoryId=checkedlist[i];
 userstoryService.delete(userstoryId);
 System.out.println(checkedlist[i]);
 System.out.println("delete#######selected inside for");
 }
       }

The goal is to retrieve the selectedIds array in the controller and store it as checkedlist array.

Answer №1

One way to handle your array is by converting it into a string format.

Use the JSON.stringify() method on your selectedIds variable.

In your controller, make sure to accept this as a String parameter and then convert it back into an array or list as needed for your specific requirements.

Best regards, Ravindra

Answer №2

One solution could be to utilize primefaces remote command feature. For more information, check out the details provided here.

Answer №3

One method to achieve this is by sending a Javascript array variable along with the form's action in order to retrieve values in the Controller.

This can be done in the controller like so:

String selectedIds[] = request.getParameterValues("selectedIds");

Ensure that the variable selectedIds = []; is declared globally.

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

What is the best method to establish a connection to an LDAP server in Java with the provided details?

I am experiencing an issue with the Java code below. Here are the details: password="some"; domain name=ABF.ADDAS.com user name=SADFA.com\username or SADFA\username Hashtable<String, String> env = new Hashtable<String, String& ...

How can I retrieve the path to a specific subnode using Javascript/JSON?

What is the best way to obtain a JSON path that leads to a specific child node within an object? For example: var data = { key1: { children: { key2:'value', key3:'value', key4: { ... } ...

Using Java's Java Cryptography Extension (JCE) to decrypt a lengthy message that has been encrypted using RSA

I have an encrypted message stored in a byte[] array, using the "RSA/ECB/PKCS1Padding" encryption algorithm. To decrypt this message, I initialize a Cipher object by calling c = Cipher.getInstance("RSA/ECB/PKCS1Padding"); So far, I've only decrypted ...

Handle form submission response from an express server using JavaScript

(Please help me with my terminology if it's incorrect.) The files server.js, run.js and index.html are all located in the same directory. server.js This file is responsible for setting up the server. const express = require('express'); ...

Transforming a collection of elements into a different set

I am currently working on the task of mapping one dataset (Set1) onto another dataset (Set2). This involves applying an operation to a subset of Set1 and then placing the result into an object in Set2. I am interested in structuring the classes in a more e ...

Check the browser's developer tools to access JavaScript files

I recently came across a server at example.noodles.com that is hosting a node.js application. I'm curious if there's a way to access the source files of this application using inspect element or some other method? Up to now, all I've been a ...

Error 403: ACCESS DENIED - The server comprehended the inquiry, yet declines to carry it out

Encountering a persistent 403 error when making an AJAX call to an API. This issue is specific to Microsoft Edge, while other browsers like IE, Chrome, Firefox, and Safari work without any errors. The page doesn't utilize bootstrap, as there have be ...

How can you effectively transfer arguments from one component to another using router.push() in Vue.js?

I need help with implementing a feature where upon clicking the edit button in a row, all the details from that particular row should be passed to a form component. I want to populate the form fields with default values from the parameters provided. Can ...

A guide to setting properties using a Proxy object

Within my class, I have included a Proxy which is structured as follows: export class Row<T extends ModelItems> { private _row: T = <T>{} public constructor(rowItems?: T) { if (rowItems) { this._row = rowItems } return new Proxy( ...

React js experiences a crash when it attempts to re-render with a different number of child elements

When working with react.js, I came across the need for a component that renders a 'tr' with either one or two 'td' elements, depending on its property. Here is an example: var Item = React.createClass({ content: function() { ...

Creating a Vue2 modal within a v-for loop to display a dynamic

Recently, I've been working on implementing a vue2 modal following the instructions provided in the official Vue documentation at https://v2.vuejs.org/v2/examples/modal.html. The code snippet I have been using looks something like this: <tbody v-i ...

What is the best way to insert spaces instead of null characters in a StringBuilder when adjusting the length?

When I utilize var.setLength(8);, the output is "55[THERE ARE 6x NULL]". Is there a simpler way to replace this function without having to manually iterate through each String and substituting it with spaces? Alternatively, can I customize the setLength ...

How is initial-data.yml loaded in Play! ORM's abstracted model interface?

My Booking model has a DateTime field that I prefer to access indirectly through two Transient String fields, date and time. However, I am encountering an issue where the data is not being loaded into these fields as expected. It seems that play framework ...

Shadows are not being cast by ThreeJS

I'm in the process of creating a simple Three JS application. As I familiarize myself with Three JS, I've been experimenting with different features. Currently, I am working on constructing a scene that includes a floor, an object, and a light so ...

The moment I attempted to send a POST method through AJAX, I encountered a 404 error. This issue occurred despite using both

I am working with Spring MVC and attempting to integrate jQuery into my project. The following code snippet is part of my web page setup: $(document).ready(function () { var entity = {mag: "status_key", paper: "View10"}; $("#btn").click(function ( ...

The process of returning parameters from a modal view in Ionic

I am currently facing an issue with my modal view that is used for user login. I need to retrieve the user id from the modal and pass it back to the view behind. I attempted using $state.go but it was unsuccessful. Additionally, using ng-href would not wor ...

Combining a complete hierarchy of Object3D/Mesh into one merged entity

I'm currently working on a project that involves dynamically generating trees using simple cubes for branches and leaves in the early prototype stages. Each tree consists of a hierarchy of cubes nested with rotations and scaling to create the final st ...

The HotRod ClientListener is failing to receive the latest view updates from the HotRod server

My situation involves 2 HotRod servers running in REPL_ASYNC mode. I am attempting to establish a connection using the hotrod client by specifying the hotrod server address and port. I am working on implementing a functionality similar to Near Cache, but ...

Encrypting passwords using both a hash function and a randomly generated salt

Currently, I am faced with the task of updating a legacy application that stored passwords in plaintext. After migrating the application to Spring 3 MVC + Security, I successfully implemented Spring Security for authentication and authorization using sha ...

Do we really need to implement ajax in this code snippet?

In my scenario, I have two JSP files named test1.jsp and test2.jsp. The flow of my program goes like this: I need to retrieve data from a textbox in test1.jsp, but the Ajax call is initiated from a different page. My objective is to receive the controller ...