Removing multiple data rows in JSP using AJAX by selecting check boxes

I have a requirement where I need to store a list of objects (each with a unique id) as a session parameter. These objects are then displayed in a table in a JSP using JSTL.

<c:forEach var="list" items="${PlayerList}">

<tr>
        <td>
<img  style="cursor:pointer" src="./images/delete.jpg" title="Force Delete" 
onClick="forceDelete(${list.playerId})">
        <td>${list.playerName}</td>
        <td>${list.runsScored}</td>
    </tr>
</c:forEach>

Additionally, there is an AJAX function that handles the deletion:

   <script>
function forceDelete(playerIdValue)
        {
            var xmlhttp;
            var toDelete = confirm("Do you want to Remove?")
            if (window.XMLHttpRequest)
            {
                xmlhttp=new XMLHttpRequest();
            }
            else
            {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {

document.getElementById('display_div').innerHTML=xmlhttp.responseText;
                }
            }
            if (toDelete == true)
            {
                xmlhttp.open("POST","PlayerController?
 value="+playerIdValue,true);
                xmlhttp.send();

            }
        }
   </script>

The process also involves handling deleting rows in the PlayerController servlet's POST method.

The next step is implementing functionality where users can select multiple checkboxes and delete the selected rows from the JSP using AJAX:

<c:forEach var="list" items="${PlayerList}">

<tr>
        <td><input type="checkbox">
        <td>${list.playerName}</td>
        <td>${list.runsScored}</td>
    </tr>
</c:forEach>
<input type="button" value="delete">

Once checkboxes are selected, pressing the delete button will trigger the respective rows' deletion through AJAX.

If any additional information is required for assistance, please let me know.

Thank you.

I've attempted to implement this feature but it doesn't seem to be working. Can you help me identify where I may be going wrong?

Checkbox code `

<input type="checkbox" name="toBeDeleted[]" value="${list.playerId}">
<div align="center"><button onclick="forceStop()">Delete</button></div>

JavaScript code

function forceStop()
        {
            var toBeDeleted = new Array();
            $("input:checked").each(function() {
            data['toBeDeleted[]'].push($(this).val());
            });

            $.ajax({
             url:"PlayerController",
             type:"POST",
             dataType:'json',
             data: {toBeDeleted:toBeDeleted},
             success:function(data){
            },
            });

`

Answer №1

Strategy to implement without revealing the specific code:

  1. Assign a name and value attribute to each checkbox, with the value being the player's ID
  2. When the delete button is clicked, gather all selected checkboxes to create an array of player IDs
  3. Send this array through an AJAX request to your servlet, which will handle the deletion of records

If needed, I can provide a pseudo code for clarification.

Answer №2

I successfully implemented this solution in my project:

When working with JSP, specifically within a JavaScript function:

function executeDeletion()
        {

            var checkboxes = document.getElementsByName('toBeRemoved');
            var selected = new Array();
            for (var i=0; i<checkboxes.length; i++) {
                if (checkboxes[i].checked) {
                    selected.push(checkboxes[i].value);
                }
            }

                $.ajax({
                    url:"PlayerController",
                    type:"POST",
                    dataType:'json',
                    data: {toRemove:selected},
                    success:function(data){
                      alert("Deletion Successful");
                    },
                });

        }

In the servlet, I retrieved the array as follows:

String[] toRemove = request.getParameterValues("toDelete[]");
    int[] toBeRemoved=new int[toRemove.length];
    for(int i=0;i<toRemove.length;i++)
    {
        toBeRemoved[i]=Integer.parseInt(toRemove[i]);
    }

It's important to convert each element to an integer since AJAX parses them as strings.

Finally, from the controller, I executed batch deletion using DAO methods.

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

Oops! Material-UI is giving an error because the data grid component needs each row to have a unique id property. There was a row provided in the rows prop that does not have an

I've encountered an error that states: Error: Material-UI: The data grid component requires all rows to have a unique id property. A row was provided without id in the rows prop: Whenever I try to add a new row to the existing rows in the DataGrid co ...

Ways to connect a click event to a dynamically generated child element with the help of jQuery?

I am aware that similar questions have been asked elsewhere, but as someone new to jQuery, I am still struggling to attach a click listener to an a element within a dynamically appended ul.li.a structure in the DOM. Below is an example of how the structure ...

Issue encountered while transferring files between a web platform and an API

Currently, I am working on two separate projects. The first project involves a website where users can upload files, and the second project is an API designed for file uploads due to the limitations of the old website. I am utilizing Laravel (6) to develo ...

Unable to retrieve JSON data in servlet

I am having trouble passing variables through JSON from JSP to a servlet using an ajax call. Despite my efforts, I am receiving null values on the servlet side. Can someone please assist me in identifying where I may have gone wrong or what I might have ov ...

An error has occurred with MYSQL/PHP/xHTTP resulting in an empty response being

I am new to this community and unsure if my issue is appropriate for this section. The website I have created relies heavily on a MySQL database. All of my SQL statements are stored in a functions.php file, where I include and call functions to execute qu ...

Form an array using the values that are returned

As I iterate through an object and extract elements, my console.log displays: ["item 1"] ["item 2"] ["item 3"] and so on. All I want is to create a new array formatted like this: ["item 1","item 2","item 3"]; ...

Issue with retrieving data using AngularJS Restangular

I've been trying to figure out how to make restangular work properly. When I call my API (using the endpoint /user) I receive the following JSON response: { "error": false, "response": { "totalcount": 2, "records": [{ "id": "1", ...

Utilize Bootstrap tooltips to display live results fetched via an AJAX call

I have a bootstrap tooltip that I am trying to populate with data from an AJAX request. The text retrieved from the request should be displayed as the title property of the tooltip. Despite successfully executing the AJAX request, I am facing two issues: ...

What is the method to alter the color of an SVG source within an image tag?

I am currently working on a component that involves changing the color of an SVG icon from black to white when a color prop is given. export class CategoryIconComponent extends React.Component { static displayName = 'CategoryIcon'; state = ...

Exploring the beauty of ASCII art on a webpage

Having trouble displaying ASCII art on my website using a JavaScript function, the output is not as expected... This is how it should appear: And here is the code I am trying to implement for this purpose: function log( text ) { $log = $('#log&ap ...

Is the next function triggered only after the iframe has finished loading?

First and foremost, I understand the importance of running things asynchronously whenever possible. In my code, there exists a function known as wrap: This function essentially loads the current page within an iframe. This is necessary to ensure that Jav ...

Begin a fresh page within a separate window, proceed to print the contents, and subsequently close the window

I am facing some difficulties with this code. I am attempting to use the "onClick" function to change the image once it is clicked, open a new page in a new window, print the newly opened window, and then close it. The issue I am encountering is that while ...

Laravel ajax crud functionality hindered by malfunctioning back button

Attempting to navigate back to the previous page is not functioning properly. Instead, I am encountering an error message that states: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (Connection: mysql, SQ ...

Using Vuejs to dynamically render a select dropdown based on the initial selection made in the first dropdown menu

I am facing an issue with two drop-down menus. The second menu's choices need to be filtered and displayed based on the selection made in the first drop-down. The RoomID value from the first drop-down is used to filter an array of objects for the seco ...

The `react-hover` npm package functions flawlessly in the development environment despite being excluded from the production build

While working on my project, I decided to utilize the npm package react-hover and it's been effective during local development in dev build. However, when I execute the npm run build command to serve the production version, the components within the & ...

What are the steps to resolve a peer dependency problem with npm?

I am facing a conflict in my package.json file with the following modules: react-router requires react 0.13.x redbox-react requires react@>=0.13.2 || ^0.14.0-rc1 After running npm install react, I ended up with version <a href="/cdn-cgi/l/emai ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

I must implement a pause in my automation script until I receive a response from an Angular HTTP request using Selenium with Java

I am a beginner in using Selenium. I'm currently working on creating a script that will log in to my website, navigate dropdown menus, click buttons, and then wait for the response of an Angular HTTP request before logging out. driver = new Chrom ...

Loop over elements retrieved from Firebase using ng-repeat

I am currently attempting to iterate through items retrieved from Firebase using ngrepeat. Although I can see the items in the console, the expressions are not working as expected. I have tried various solutions, but nothing seems to be working. Any assist ...

jquery and radio button technology

I am attempting to create a basic function using jquery, but it is not functioning properly. Here is the radio button in question: <input type="radio" id="price" name="shipping" class="styled" /> In the head section of my HTML, I have included the ...