Revitalizing JSP Table with jQuery & Ajax: The Ultimate Guide

I'm a beginner in the field of web development.

Currently, I have developed an application using Spring MVC and JSP. However, when my page reloads after submitting a form, which is not the desired behavior.

I would like to implement jQuery and Ajax to dynamically update my table without having to reload the entire page.

This is a snippet of my JSP code:

    <form action="<c:url value="/admin/apw/ssar"/>" method="get" name='SsarTable' > 

            <div class="col-md-1">
                <!-- Submit button -->
                <div class="form-group">
                    <button class="btn btn-primary " name="submit" type="submit">Search</button>
                </div>
            </div>
                            <table id="example1" class="table table-bordered table-striped">
                                <thead>
                                    <tr style="background-color:#dedede;">
                                        <th data-field="tno">NO</th>
                                        <th data-field="seqplan">PLAN</th>
                                        <th data-field="seqactual">ACTUAL</th>
                                        <th data-field="evaluate">EVALUATE</th>
                                        <th data-field="remark">REMARK</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <c:forEach items="${lists}" var="ssar">
                                        <tr>
                                            <td>${ssar.tno}</td>
                                            <td>${ssar.seqplan}</td>
                                            <td>${ssar.seqactual}</td>
                                            <td>${ssar.evaluate}</td>
                                            <td>${ssar.remark}</td>
                                        </tr>
                                    </c:forEach>
                                </tbody>
                            </table>

Here's the relevant snippet of my controller:

@RequestMapping(value = "/apw/ssar", method = RequestMethod.GET)
public ModelAndView getSsarTable(@RequestParam(required = false, value = "plandate") String planDate) {

    ModelAndView model = new ModelAndView("apw/ssar/table");

    List<Ssar> list = ssarService.getSsarTable("J20", planDate);
    model.addObject("lists", list);

    logger.info(authService.getAuthenticatedAdmin() + " executed getSsarTable()");
    return model;
}

I would greatly appreciate any assistance in modifying my code and implementing an Ajax script for this functionality. Thank you!

Answer №1

Here's an example from one of my projects:

Data Table

<button class="accordion" onclick="fetchSchedule()">View Schedule</button>
<div class="panel">
    <table id="scheduleTable" align="left" class="order-table" style="width: 50%">
        <thead>
        <tr>
            <th align="left">Subject</th>
            <th align="left">Date</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

AJAX Request

function fetchSchedule() {
            $.ajax({
                type: "GET",
                url: 'retrieveSchedule',
                dataType: "json",
                complete: [
                    function (response) {
                        $("#scheduleTable").find("tr:not(:first)").remove();
                        var trHTML = '';
                        var obj = $.parseJSON(response.responseText);
                        for (var i = 0; i < obj.length; i++) {
                            trHTML += '<tr><td><label>' + obj[i].subject + '</label></td><td>' + obj[i].stringDate + '</td></tr>';
                        }
                        $("#scheduleTable tbody").append(trHTML);
                    }
                ]
            });
        }

Controller Method

    @RequestMapping(value = "/retrieveSchedule", method = RequestMethod.GET, produces = {"application/json"}, headers = "Accept=*/*")
    @ResponseBody
    public List<Lesson> displayScheduleForLecturer() {
        List<Lesson> list = daoLesson.getLecturerLessons(new Lecturer(ID, login.getNickname(), login.getPassword()));
        Collections.sort(list);
        return list;
    }

EDIT To pass additional parameters, you can include them in your AJAX request (after the "dataType" field)

data: {id: "someId"},

Then retrieve them in your controller using:

@RequestMapping(value = "/fetchSubjectsForMemberGroup", method = RequestMethod.GET, consumes = "application/json", produces = {"application/json"}, headers = "Accept=*/*")
    @ResponseBody
    public List<Subject> getSubjectsForMemberGroup(@RequestParam("id") int id) {
        Object object = new Object(id);
        return daoSubject.retrieveSubjectsForMemberGroup(object);
    }

Alternatively, you can create a variable to hold the data you wish to pass:

var lecturer = {
                    id: document.getElementById("lecturerId").textContent,
                    name:  document.getElementById("lecturerName").value,
                    login:  document.getElementById("lecturerLogin").value,
                    password: document.getElementById("lecturerPassword").value,
                    info:  document.getElementById("lecturerInfo").value,
                    degree:  document.getElementById("lecturerDegree").value,
                    works: document.getElementById("lecturerWorks").value,
                    interests:  document.getElementById("lecturerInterests").value,
                    cathedra:document.getElementById("selectCathedraOnEdit").options[document.getElementById("selectCathedraOnEdit").selectedIndex].text,
                    cathedraId:document.getElementById("selectCathedraOnEdit").options[document.getElementById("selectCathedraOnEdit").selectedIndex].value
                }

Then pass it using AJAX:

data: JSON.stringify(lecturer),

Finally, retrieve the data in your controller:

@RequestMapping(value = "/updateLecturer", method = RequestMethod.POST, consumes = "application/json")
    @ResponseStatus(value = HttpStatus.OK)
    public void modifyLecturer(@RequestBody Lecturer lecturer) {
        daoLecturer.updateLecturer(lecturer);
        daoObject.updateObject(new Object(lecturer.getId(), lecturer.getName(), "lecturer", lecturer.getCathedraId()));
    }

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

Display upon hovering, conceal with a button located within a popup container

There seems to be an issue with the code below. Even though it works perfectly in jsfiddle, it breaks in my Chrome and other browsers right after displaying the ".popup" div. Can anyone point out what I might be doing wrong? I found similar code on this si ...

Carousel-Owl, glide through two items simultaneously

I am currently in the process of developing a slider using the beta version of Owl-Carousel 2, but I am encountering several issues. My goal is to configure the owlCarousel to function as follows: It should scroll through 2 items at a time while displayin ...

The Custom Validator encounters an issue retrieving the Combobox identification

I have encountered an issue where the Required Field validator fails for the Ajax Combobox, so I decided to use a custom Validator instead. However, I am facing difficulties in getting it to work with the Combobox. Interestingly, when I pass the Id of anot ...

The outcome of a function within the $.ajax method is transformed into a string

Trying to pass an array of IDs using the $.ajax data variable is proving to be a challenge. The array is generated by a function, and I've noticed that if I define this function outside of the $.ajax call, it works fine. However, when I place the same ...

What is the best way to utilize jspdf for formatting data, specifically when wanting the first column to be in bold?

How can I customize data formatting using jspdf? Specifically, I would like the first column to be in bold and the second column in normal text. Additionally, I want to align them in the middle of the pdf output with different colors for each column. Belo ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...

Initiate the Html.BeginForm process in an asynchronous manner

Within my ASP.NET MVC 3 application, I am attempting to upload a file using the Html.BeginForm helper, as shown below: <% using (Html.BeginForm("ImportFile", "Home", new { someId = Id }, FormMethod.Post, new { enctype="multipart/form-data" } )) %> ...

Enhancing the functionality of hidden input fields using jQuery

I'm looking to dynamically update the value of a hidden input element when a button is clicked. Here's what I have so far: Hidden Input Element: <input type="hidden" value="action" id="action" /> Buttons: <INPUT name=submit value=~#S ...

Regularly check in with the server via ajax calls

I have a page that needs to send periodic "background" ajax requests after it is loaded. These requests should be sent at specific time intervals. Would using cron be the best option for this task, considering that I have never used it before? Are there a ...

Unique Javascript Library Focused on AJAX

Looking for a specific JavaScript library that focuses solely on AJAX functionality, such as a basic XMLHttp wrapper. ...

Multi-Slide AngularJS Carousel

My current setup includes a carousel like so: <div> <carousel id="myC" interval="3000" > <slide ng-repeat="order in orders"> <img ng-src="whatever.jpg" style="margin:auto;"> <div ...

Having trouble passing multiple parameters in a jQuery AJAX request?

I'm currently working on implementing a .NET web service (asmx) using JSONP with guidance from this helpful tutorial. When I try calling my webservice with only one parameter, everything runs smoothly. However, the moment I attempt to call it with mu ...

Utilize jQuery to swiftly align elements within a designated container

Check out my JSFiddle example: http://jsfiddle.net/c62rsff3/ I'm attempting to implement snapping behavior between 2 elements using this code: $('.draggable-elements').draggable({ snap: true }); In addition, I've defined a container ...

"The jQuery Validate plugin allows for dynamic selection of error elements based on specific

Currently, I am utilizing the jQuery Validation Plugin for my project. My goal is to dynamically determine the errorElement, based on the type of element that contains an error. By default, you can set the errorElement like this: $("form").validate({ ...

The AJAX request to the URL is failing

Creating a webpage with the ability to control an IP camera's movements such as moving up and down or zooming in and out involves calling specific URLs. While trying to implement this feature asynchronously, I encountered issues using AJAX which did n ...

The jQuery slider fails to showcase its content

After careful consideration, I decided to start with a small project... But unfortunately, it didn't work. For some reason, the jQuery UI slider won't display on this page. What could be the issue? I made sure to include the jQuery library in ...

Retrieve webpage using HTML stored in web storage

I am exploring a new idea for an application that utilizes local storage, and I am seeking guidance on the most effective way to load content after it has been stored. The basic concept of the app involves pre-fetching content, storing it locally, and the ...

Help needed with parsing nested JSON using the $.each function

Here is a JSON response sample that needs to be parsed in a more generic manner, rather than using transactionList.transaction[0]. "rateType": interestonly, "relationshipId": consumer, "sourceCode": null, "subType": null, "transactionList": { "transac ...

Quiz application utilizing MySQL and JSP technology

I've been developing a Web Application using JSP to host MCQ quizzes. The questions are stored in a MySql Database table called 'qna', with each question having 10 choices. My goal is to design the quiz so that each question appears on a new ...

convert webpages and images to PDF with a custom watermark

Looking to convert images fetched from the server into PDF format with a watermark by clicking a button. It would be ideal if there is a plugin that allows for PDF preview with disabled user selection and copy options. The website's platform is Sales ...