Spring MVC: Implementing AJAX call to dynamically render a page from ModelAndView

Currently working on a project with Spring MVC, I am looking to pass a JSON object from one page to another. My approach involves creating a controller where the object is sent via a POST AJAX call. The controller then constructs a ModelAndView object for the next jsp page, includes the object as an attribute, and returns it. Now, the challenge lies in redirecting to the ModelAndView-rendered page. See below for the relevant code snippet:

Controller:

public ModelAndView nextPageController(@RequestBody String passedJsonString) {
    ModelAndView nextPage = new ModelAndView("/nextPage.jsp");
    nextPage.addObject("passedJsonString", passedJsonString);
    return nextPage;
}

AJAX Call:

            controllerUrl = "/controller/path";
            $.ajax({
                type : "POST",
                headers : {
                    'Accept' : 'application/json',
                    'Content-Type' : 'application/json'
                },
                url : controllerUrl,
                data : JSON.stringify(jsonDataToBePassed),
                success : function(dataString) {
                    console.log(dataString);
                }
            });

The AJAX call completes successfully and the expected ModelAndView object is returned. However, now the task is to display the next page with the added controller attributes intact. I acknowledge that my current method may not be optimal, so any suggestions on achieving this more efficiently would be greatly appreciated.

Answer №1

When an ajax call is made to a controller, it expects a response to proceed accordingly.

In this scenario, the response is returned to the ajax function after successful execution by the controller.

If you wish to redirect to another page, you can create a method in the controller that returns the desired page (/nextPage.jsp).

So, include the following code snippet in your implementation:

success : function(dataString) {
      window.location.href = "/path/of/controllerMethod"; //redirects to the controller method which returns the JSP page
}

And define the method as shown below :

@RequestMapping(value="/path/of/controllerMethod")
public ModelAndView returnJspPageControllerMethod() {
    ModelAndView nextPage = new ModelAndView("/nextPage.jsp");
    return nextPage;
}

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

Is there a clear definition of behavior when using non-Promise values with Promise.all?

Are the behavior of Promise.all() docs guaranteed in Node when non-Promise values are passed? For example, using Node 6.10.2: Promise.all([1, 2, 3]).then( res => console.log(res) ); In this scenario, it prints [ 1, 2, 3 ], but is it sure that Promis ...

The phpmailer is not functioning properly after sending the code variations

Hey there, I am currently working on four pages: 1. config file 2. form file 3. form execute file 4. send php mail file Everything is running smoothly until I introduce the PHPMailer code. After the send mail code, the rest of the code stops working. An ...

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

What is the method to verify if an AJAX request has already been initiated using Jquery?

Currently, I have implemented an Ajax request using Jquery to submit a form. $.ajax( { type: "POST", url: "login.php", data: $("#signin").serialize(), dataType: "json", cache: false, ...

"Please note that the function of the enter key to navigate between form fields is

When I use the enter key to move between form fields, it's not working as expected: The cursor doesn't move to another field in the form when I press the enter key. Removing the submit button allows the enter key to work properly. The issue se ...

Discovering the size and count of JavaScript objects within a browser's memory

Many suggest using the Chrome Profiler Heap Snapshot to analyze memory usage, but I have found that on an empty page (no JavaScript or CSS, just HTML), it shows a heap size of 8MB and anywhere from 12 to 30 thousand objects depending on its mood. This tool ...

Using JQuery to rebind() after resetting the count

In my game, I have implemented a feature to ensure that the start button can only be clicked once each time it appears in order to prevent the function from loading multiple times. I wrote some code that tracks the number of clicks and unbinds the click e ...

Having trouble connecting to Azure SQL server from my Node.js application

I'm attempting to run a basic query to my Azure SQL server from NodeJs, but I'm encountering errors indicating that I cannot establish a connection to the server. The details provided in my code are correct because I've used them successfull ...

Error in Angular: Http Provider Not Found

NPM Version: 8.1.4 Encountered Issue: Error: Uncaught (in promise): Error: Error in ./SignupComponent class SignupComponent_Host - inline template:0:0 caused by: No provider for Http! Error: No provider for Http! The error message usually indicates the a ...

Contrasting {} and {} as any in TypeScript

Seeking clarity on TypeScript, what sets apart (foo and foo2) from (foo3 and foo4)? (foo and foo2) as well as (foo3 and foo4) produce identical results, yet during compilation, a red underline appears under foo2 and foo3. https://i.stack.imgur.com/lWaHc. ...

Create various React Native bundles using a single source code base

Suppose I have a React Native application with various features, such as News, Products, and User authorization. I'd like to create two versions of the app: a "free" version that only includes News, and a "pro" version that contains all features. How ...

Angular's ng-maxlength feature will indicate that a field is invalid if it is left blank, even if it contains any characters

Currently, I am developing a dynamic form using Angular (1.3b17). In my approach, I store the form's schema in an object with various properties defining field behavior like "type" (text, textarea, check, etc) and "maxlength." Subsequently, I assign t ...

Caution: PropType validation failed - The prop `rrrr` provided to `sportsMockUpStandard` is not valid

https://gist.github.com/js08/dfeab2df8b68240297eb I am currently working on creating a test case for a jsx file. While I have successfully passed proptypes in some cases, there are instances where I face errors due to incorrect prop handling. The error ...

Django: The number remains static following the ajax request

To avoid creating a duplicate post, I am revising this question. The initial comments pertain to the original query. I am working on a Django project for an exam, where part of it involves building a site with notes that logged-in users can vote on. Alth ...

Transferring query parameters to a new page using the POST method in a Node JS and Express application

I'm experiencing an issue where I need to pass the same id through multiple consecutive web pages using query parameters. While transferring the param with GET routes works fine, I encounter a problem on the third page which has a short form and uses ...

Having difficulty displaying a partial view within a view while making an AJAX call

Trying to figure out what's missing in my code. I have a view with some radio buttons and I want to display a different partial view when a radio button is selected. Here's the snippet of my code: Controller public ActionResult Method(string va ...

Steps to utilize jQuery Masonry Plugin for organizing images

Struggling to put together a straightforward image gallery that can accommodate images of different sizes, I stumbled upon masonry in my quest for a plugin that could help with that. After attempting to create a prototype of this idea using a masonry empt ...

Is there a way to effectively combine @Model and @Emit in VueJs using Typescript?

I could really use some assistance with @Model and @Emit decorators. I'm attempting to alter the order on click within my component, and I referred to the documentation found here: https://github.com/kaorun343/vue-property-decorator. Below is the code ...

Ensuring the accuracy of phone numbers with the power of AngularJS

Is there a way to ensure that the phone number input is always 10 digits long using AngularJS? This is my attempted code: <form class="form-horizontal" role="form" method="post" name="registration" novalidate> <div class="form-group" ng-class= ...

Utilizing reference memory to enable communication between two controllers

Within my Angular application, I have implemented a service to facilitate communication between 2 controllers and allow them to share the input variable from the search box. I am using kickSearch.box to reference memory...obj.property. However, there seem ...