Page transitions spring boot program

I am encountering an issue when trying to navigate between pages. I have a button that triggers an AJAX POST request. Here is an example of the code:

 $.ajax({
        contentType: "application/json",
        type: "POST",
        data: JSON.stringify(project),
        url: "/saveProject",
        success: function (data) {
            console.log('done');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('error while post');
        }
    });

@RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public @ResponseBody
String saveProject(@RequestBody Project newProject, Authentication authentication) {
    projectService.saveProjectNew(newProject, authentication);

    return "mywork.html";

}

My goal is to redirect to mywork.html after executing the AJAX call, but currently nothing happens and I remain on the same page. There may be something missing in my implementation that I am not aware of, as I am relatively new to this.

Answer №1

In order to redirect the page to mywork.html, you must include the following code within the success function of your Ajax call:

window.location.href = "Your context path"+"/mywork.html";

Refer to the example code snippet below for guidance:

$.ajax({
    contentType: "application/json",
    type: "POST",
    data: JSON.stringify(project),
    url: "/saveProject",
    success: function (data) {
        window.location.href = "Your context path"+"/mywork.html";

    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('error while post');
    }
});

Keep in mind that the spring web client code will not directly route the call to mywork.html. All redirections should occur through the Ajax call.

return "mywork.html";

This code is specifically for modeling the response obtained after calling the endpoint.

Answer №2

When it comes to triggering HTTP redirection, it can be done from both the back-end and the front-end AJAX code as shown in your post.

If you want the redirection to occur from the user interface, you can include a window redirection like @Anurag suggested in his response within the AJAX success callback.

In the example provided, you are attempting to redirect the user to a new page directly from the backend endpoint itself. To make this redirection work from the Spring backend side, where you already have a controller returning the view for mapping /mywork.html, you need to follow these steps:

@RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public String saveProject(@RequestBody Project newProject, Authentication authentication) {
    projectService.saveProjectNew(newProject, authentication);
    return "redirect:/mywork.html";
}

Alternatively, you could use ResponseEntity like so:

HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(newUrl));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);

In your current implementation, the use of the annotation @ResponseBody for the controller method results in the endpoint behaving like a REST endpoint that returns JSON by default. To enable redirection, remove this annotation and transform it into a standard controller method that returns a view.

If you still wish to perform redirection from a REST endpoint, you can utilize HttpServletResponse in this manner:

@RequestMapping(value = "/saveProject", method = RequestMethod.POST)
public @ResponseBody String saveProject(@RequestBody Project newProject, Authentication authentication, HttpServletResponse response) {
    projectService.saveProjectNew(newProject, authentication);
    response.sendRedirect("url-here");   
}

For further details, check out this link.

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

Experiencing issues with the session not functioning properly on the login page

After setting up Centos 6.4 on my HP Server with PHP 5.3.3, Apache 2.2.15, and Mysql 5.1.69, I encountered login issues where it always fails. Here is the source code: index.php <? include "functions.php"; start_session(); session_destroy(); start_ ...

How to Align Text at the Center of a Line in Three.js

Exploring What I Possess. https://i.sstatic.net/nAtmp.png Setting My Goals: https://i.sstatic.net/svcxa.png Addressing My Queries: In the realm of three.js, how can I transform position x and y into browser coordinates to perfectly align text in th ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

Executing functions in real-time using React Native

I'm fairly new to Object-Oriented Programming (OOP) and my understanding of promises, asynchronous/synchronous function execution is quite basic. Any guidance or help from your end would be greatly appreciated! Let's take a look at an example fr ...

The RadImageEditor onSaving Event does not permit the sending of response scripts

I am using a custom RadImageEditor control with a version of 2013.1.220.40. The control is placed on a page and displayed in a RadWindow. My goal is to either pass a URL or not pass it (for Update and Add scenarios, respectively). After cropping the image ...

Ionic: How come my image is not loading with HTTP.GET?

I have been attempting to populate a gallery in my Ionic application by fetching images from a JSON file, but I am encountering issues. While following a guide on creating a grid-like image gallery using the Ionic framework (https://blog.nraboy.com/2015/03 ...

Optimal Method for Organizing Items in Express.js Using Mongodb

Can you share your insights on the best practices for sorting objects in expressjs + mongodb(mongoose) web applications? Imagine we have a Product model with four attributes: var ProductSchema = new mongoose.Schema({ name: String, // "Summer T-sh ...

Create a circle-shaped floor in THREE.JS that mimics the appearance of a shadow

I am working on creating a circle mesh with a gradient material that resembles a shadow effect. Specifically, I want the circle to have a black center and fade to almost white at the edges. Currently, I have been able to create a circle and position it co ...

The Mongoose framework captures and stores all input parameters from the request body

Currently in the process of setting up a small API, I am handling data validation on the client side of my application. As I go through this process, I am also organizing my data to align with my mongoose schema. My current attempt involves... router.rou ...

Establish a reference to a newly created instance of a class

In my project, there is an Enum structure as shown below: public static enum TestEnum { // main ENUM_A (1, "test1", TestADto.class), ENUM_B (2, "test2", TestBDto.class), ENUM_C (3, "test3", TestCDto.class), ... private Class< ...

When running the command `npm start`, an error message is generated

Hey everyone, I've been trying to learn some basic AngularJS 2.0 skills through a tutorial. Unfortunately, when I tried running the command npm run start, it didn't work as expected. I'm currently using Git Bash on Windows 10 OS. If you hav ...

Tips for gathering an array of checkboxes within a dynamic array of items using Vue.js and Vuetify

I am currently working on a role permission system where I have defined a resource array containing items that users can access, as well as checks representing the permissions for each resource. My goal is to dynamically assign a role with these resources ...

Using Node.js, Socket.IO, and Express to deliver static JavaScript files served dynamically

I have been working on a node.js application that utilizes socket.io and express. Initially, all of the javascript was included in the HTML file, but now I am looking to separate it into a .js file. In my primary node application, this is what I currently ...

Can you transform your content like Google does?

Looking to create a help page with a layout similar to http://support.google.com/plus/?hl=en. Can anyone provide advice or an example of how to update the new content list without refreshing the page? When you click on something like "circles and streams" ...

The XML content fails to display after initiating an AJAX request

Attempting to create an ajax call and accessing a field from the table on the server yields the following: <PushProperty><Status ID = "1"> Success </Status><ResponseID> b3633c9eeb13498f </ResponseID><ID> 9098 & ...

Tips on displaying a modal pop-up at the center of the screen while also keeping its position intact when the screen is resized

I have a modal pop-up that I am displaying in the center of the screen using JavaScript. $('div.openIDPopup').css({ 'height': $(document).height() + 'px', 'width': $(window).width() + 'px', ...

Why is my JQuery async callback running unbelievably slow?

Exploring Ajax with manual jQuery for the first time, not exactly loving it but definitely better than a full page refresh. I encountered an extremely trivial edge case. Like, seriously trivial. There's a backend method in the controller to update s ...

NodeJS is capable of handling a limited number of requests at a time

Utilizing jQuery to send requests to a local server has been causing some issues. After sending approximately 4-7 requests, the port stops working without any visible error. Eventually, after a few minutes, some of the requests are successfully sent to the ...

The AJAX request becomes stuck in the beforeSend function

$(document).ready(function(){ $('.gbutton').click(function(){ text=$("#textid").val(); $.ajax({ type: "POST", url : "postquery.php", data: "text="+text, beforeSend: function(){ $('# ...

Generate random positions for several divs using jQuery

Here is my code snippet: http://jsfiddle.net/BREvn/2/ (it's functional). However, I want each div to have a unique position coordinate. Currently, the script moves others to the place of the first one. How can I resolve this issue? I attempted using a ...