Make sure to refresh the model using an Ajax request in Spring MVC

I have a page where I use AJAX to insert data into my database. On that same page, I display a table of records that are inserted. Each time I add a new record, I want to update the content of the table. Here is what I have implemented:

@RequestMapping(value="/add_record",method=RequestMethod.POST)
public @ResponseBody String addUser(@ModelAttribute User us,BindingResult result,ModelMap model){
    userService.AddUser(us);
    model.addAttribute("usersystem", userService.getAllUsers()); // <== Issue here
    return "You have successfully added a record!";
}

The jQuery function:

function doAjaxPost() {
    var frm = $('#ajf');
    frm.submit(function (event) {
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "${pageContext.request.contextPath}/add_user",
            data:  frm.serialize(),
            success: function(response){
                $('#info').html(response);
            },
            error: function(e){
                alert('Error: ' + e);
            }
        });
    });
}

I am struggling with returning the attribute added by the controller to my JSP page without having to refresh it every time. Is there a way around this?


Alternatively, if I modify the code like below:

@RequestMapping(value="/add_record",method=RequestMethod.POST)
public @ResponseBody ModelAndView addUser(@ModelAttribute User us,BindingResult result,ModelMap model){
    ModelAndView modelAndView = new ModelAndView("jspName");
    userService.AddUser(us);
    modelAndView.addObject("usersystem", userService.getAllUsers()); // <== Issue here
    return modelAndView;
}

Is there a way to receive this model in the AJAX call?

Answer №1

It is recommended to return the desired data as @ResponseBody or a ResponseEntity instead of adding it to a Model. This way, Jackson (or similar tool) will automatically serialize it to JSON for easy consumption in your front-end success/done callback. AJAX requests are essentially service endpoints and not part of the MVC flow.

Answer №2

Here's the approach I would take:

     @RequestMapping(value="/add_entry",method=RequestMethod.POST)
        public String createUser(@ModelAttribute User user, BindingResult result, Model model){
             userService.addUser(user);
             model.addAttribute("systemUsers", userService.getAllUsers());
             model.addAttribute("message", "Record added successfully!");
             return "YourPageName :: #info"; // This will specifically target the info section of your page.
        }

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

Having a problem with the xmlhttprequest, not confident if it is being called correctly

I encountered a problem with the code I have where a user selects a sales center and it should trigger a currency change. Both selections are dropdowns, but when I choose a sales center, I receive an error saying ReferenceError: makeRequest is not define ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

Content that moves with a flick of a finger

Seeking advice on a widely used JavaScript library that can facilitate scrolling for frequently updated content, similar to what popular websites like have implemented. I've had difficulty finding the right query on Google, so any recommendations or ...

Incorporate a class into the fixed navigation menu using fullpage.js

I am attempting to modify the behavior of a sticky menu as the user scrolls down using fullpage.js. My goal is to have the #top-wrapper behave normally when the first section/page loads, and then add a class of is-fixed as you scroll down. When scrolling ...

Struggling to choose an element within $(this) despite being able to view it in the $(this) outerHTML

I have a question regarding jQuery 1.12. I am attempting to target an element within $(this). $(".select").bind('keydown', function(event) { elt = $(this)[0]; console.log(elt.outerHTML); elt = $(this)[0].search("li") console.log ...

The current issue with Ajax and setInterval() is that the automatic updating of the text file is not

I am encountering an issue with updating two text files displayed on a web page through ajax. The script works perfectly on my localhost, but fails to update the files when hosted online. I have disabled caching of the ajax response, but still facing the s ...

I am wondering if there is a way to utilize jquery tsort in order to sort an unordered list while having only the ul as

Typically, when utilizing tsort to sort a ul, the syntax is as follows: $('ul>li').tsort(); In my case, I have access to the ul through a variable created like this: var myul=$('#mydiv').find('ul'); My question is, how ...

Problematic PHP/AJAX: How come my getAttribute function is only selecting the initial line within the foreach loop?

My goal here is to display a list of users, each with a button that sends unique IDs to the database. The issue I'm facing is that the code only works for the first user in the list and not the rest. I suspect this is because every list item has the s ...

Error message: Unable to access .exe file through HTML link

We have a need to include an HTML link on our intranet site that, when clicked, will open an .exe file that is already installed on all user machines. I attempted the following code: <a href = "C:\Program Files\Cisco Systems\VPN&bsol ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

unable to transmit form data through ajax using a JSON object

I've been attempting to send JSON data via AJAX in a Jersey API, but I'm encountering difficulties with sending the data. Below is my code: Javascript Code var jsonObj = createDataObj(); $.ajax({ type : "POST", ...

Selecting radio button does not update corresponding label

I am having an issue with setting a radio button as checked. In the example snippet, it works perfectly fine but on my localhost, it is not working. Even though the input gets checked, the label does not change. Surprisingly, if I set another radio button ...

Learn the process of using calc to rotate images on hover with CSS and Jquery

Is there a way to implement the rotate on hover function for images, similar to what is seen on this website under 'our Latest Publications'? I attempted using calc and skew, however, I was unsuccessful in achieving the desired hovering effect o ...

Generating and Retrieving Dynamic URL with Jquery

My web page named single-colur.html has the ability to handle various query strings, such as: single-colour.html?id=1 single-colour.html?id=2 single-colour.html?id=3 single-colour.html?id=4 The parameter id in the URL corresponds to an entry in a table c ...

Developing a system mode called "night mode"

I've decided to incorporate a dark mode feature into my Wordpress theme. Creating both dark and light modes was a breeze, but now I want to add a third mode that serves as the default for pages. This new mode will automatically switch between dark a ...

The bubble dialogue box in my picture

Looking to create a panel with images that, when clicked on, display an info window similar to Google Map's pin maker. When you click on an image, a balloon should appear containing additional information. Check out this example <a id="infowindow ...

What could be the reason for the failure of this click binding to get bound?

Take a look at this fiddle: http://jsfiddle.net/BxvVp/11/ I have created a view model with a function that replaces the content of a div with some hidden content on the page. After this replacement, the text binding seems to work fine, but the click bindi ...

What could be the reason for Google Maps producing a static map instead of a dynamic one?

Here is a snippet of code that showcases Google Map integration: <div class="col span_1_of_3 gMapHolder"> </div> Utilizing JQuery: $(document).ready(function () { alert($(".mapUse").text()); var k = $(".mapUse").text(); var embed ...

Reduce the complexity of the regular expression

Hey there, I'm having trouble with email validation using regExp. Can someone give me a hand? These are the requirements: Uppercase and lowercase Latin letters (a-z, A-Z) Digits 0 to 9 Special characters: # - _ ~ ! $ & ' * + = and p ...

Using an Ajax call within an event handler function

After spending a full day attempting to execute an AJAX call within an event handler function, I've tried various combinations of when(), then(), and done(), as well as setting async: false. However, I keep encountering undefined errors despite my eff ...