1

I have a controller in a springboot application that works perfectly fine in the normal use case, which is calling it via html form eg. like that:

<form action="/controllerURL" method="post" enctype="multipart/form-data" id="uploadForm">

But for one use-case I have to make the call via Ajax like this:

$.ajax({
url: "/controllerURL",
type: "POST",
data: new FormData($("#uploadForm")[0]),
processData: false,
contentType: false,
dataType: "text/plain;charset=UTF-8",
cache: false,
success: function () {
  // Handle upload success
  // ...
},
error: function () {
  // Handle upload error
  // ...
}
  });
}

This call only works partially. The normal execution code in the controller works. Controller code:

@RequestMapping(value = "/controllerURL", method = RequestMethod.POST)
public String someMethod(Model model, RedirectAttributes redirectAttributes,
        @RequestParam("editorText") String editorText) {


//Some code that is executed propperly

    redirectAttributes.addFlashAttribute("saveSuccess", true);
    return "redirect:/editor";
}

Now the problem is that the redirect is not being executed when the call is made via the above mentioned ajax method. I was thinking if I might be able to do something special in the success/error methods but couldn't come up with something. I need the redirect to be executed in order to load the page new and display content based on the result of the code in the controller (that's also the reason for the redirectAttributes).

Does anyone have an idea on how I can change the behaviour to be the same as the call via HTML Form ?

Claudio Brasser
  • 511
  • 3
  • 20
  • You could check if the AJAX returned a 301, and if so, set the window.location to be the value of the Location header returned. – Zachary Craig Dec 26 '17 at 12:01
  • window.location.href = /redirect/page and check this https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call – sashok_bg Dec 26 '17 at 15:57

0 Answers0