I have a method GET in js
$(".btn-sm").click(function() {
$.ajax({
url: '/check_rating/'+this.value,
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
});
url is such like this /check_rating/1. Controller
#RequestMapping(value = "/check_rating/{id}",method = RequestMethod.GET)
public String check_rating(#PathVariable("id")Long id, RedirectAttributes redirectAttributes){
List<Rating>rating = ratingService.findAllRatingsByIdStudentAndStageOfApproveGreaterThan(id,0);
redirectAttributes.addFlashAttribute("rating",rating);
return "redirect:/students_rating";
}
#RequestMapping(value = "/students_rating",method = RequestMethod.GET)
public String student_rating(#ModelAttribute("rating") List<Rating>rating, ModelMap model){
model.addAttribute("rating",rating);
return "students_rating";
}
}
I need redirect to /students_rating, but after sending get method by url /check_rating/1 i still remain on the same page and redirect is now working, but on console i have log such this
MODEL = {rating=[student_rating.entity.Rating#7856e7f, student_rating.entity.Rating#6a369ebf, student_rating.entity.Rating#7ed68627], org.springframework.validation.BindingResult.rating=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'students_rating'; URL [/pages/students_rating.jsp]] in DispatcherServlet with name 'dispatcher'
DEBUG o.s.web.servlet.view.JstlView - Added model object 'rating' of type [java.util.ArrayList] to request in view with name 'students_rating'
o.s.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.rating' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'students_rating'
o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'requestDataValueProcessor'
o.s.web.servlet.view.JstlView - Forwarding to resource [/pages/students_rating.jsp] in InternalResourceView 'students_rating'
o.s.web.servlet.DispatcherServlet - Successfully completed request
o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
students_rating.jsp
<tbody id="tBody">
<c:forEach items="${requestScope.rating}" var="rating">
<tr><td class="column"><c:out value="${rating.id}"></c:out></td><td><c:out value="${rating.date}"></c:out></td><td><c:out value="${rating.score}"></c:out></td></tr>
</c:forEach>
</tbody>
You can not redirect page with Location header for ajax requests. You must get some response text for ajax and redirect user using parsed response text. This is how to redirect browser with JS code
if (responseText == 'OK') {
document.location.href = 'http://example.com/';
}
If you are hitting controller using AJAX request then Your Spring mvc controller should return some response and based on the response you can redirect the request in your view page.
Update ajax call to below code :
$(".btn-sm").click(function() {
$.ajax({
url: '/check_rating/'+this.value,
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
if (responseText == 'OK') {
window.location.href = '<--replace this with controller URL-->';
}
},
error: function () {
alert("error");
}
});
});
You could use document.location.href but it is deprecated in html5.
Related
I have a form that I am submitting using AJAX:
var formData = JSON.stringify($('#supportrequest').serializeArray());
$.ajax({
type: "POST",
url: "/updatesupportrequest?bugid=" + $('#requestnum').val(),
data: formData,
success: function(){
console.log("success");
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
},
complete: function(){
console.log("complete");
},
dataType: "json",
contentType : "application/json"
});
This is picked up by my Spring Boot controller:
#PostMapping("/updatesupportrequest") // Called by the form
public String createSupportRequest(#RequestParam(name = "bugid") int bugid, #RequestBody String requestBody,
Model model) {
System.out.println(bugid);
DatabaseWriteResponse response = writeToDatabaseService
.writeToDatabase(WriteToDatabaseService.PROCEDURE_UPDATESUPPORTREQUEST, requestBody);
System.out.println(response.getResponse());
if (response.getResponse().equals(DatabaseWriteResponse.SUCCESS)) {
return "supportrequest";
}
else {
model.addAttribute("response", response.getResponse());
model.addAttribute("errorMsg", response.getMsg());
return "error";
}
}
The actual saving of the data works just fine. The problem is that the controller returns the "supportrequest.html" page. AJAX then throws a parse error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Looking at the xhr.responseText, we get the page back:
responseText: "<!--\r\n TODO\r\n - Dev page has some different fields \r\n\r\n\r\n -->\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n<head>\r\n<title>Support Center</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html;
I either need the page to redirect properly (which works fine on Get, just not Post) or to be able to return an empty JSON string and trigger the AJAX success function. I don't particular care which - I can handle the result either way. I just can't get either option to work. What am I doing wrong?
If you want to return JSON in a #Controller class, then annotate the return type of the method with #ResponseBody.
I am creating Spring mvc app. I am submitting JSON string to controller through AJAX. What I want is to redirect the page to different JSP page.
Right now I am returning the view from controller but instead of redirecting it is returning response to previous AJAX request.
Spring Controller
#RequestMapping("/hello")
public String hello() {
return "powerseries";
}
Javascript/Ajax
$(document).ready(function(){
$('#getData').click(function(){
var aa=JSON.stringify(answer);
$.ajax({
type: "POST",
url: "hello",
contentType: "application/json",
dataType:'json',
data:aa,
cache: false,
processData:false,
success: function(status){
console.log("Entered",status);
},
error:function(error){
console.log("error",error);
}
});
});
});
console.dir(answer);
Browser Console
When you are using AJAX, your MVC should return a special JSON response.
eg:
#RequestMapping("/hello")
#ResponseBody
public Map hello() {
m.put('my_redirect', 'the new url');
return m;
}
then handle this response in your AJAX's handler. Use javascript's window.location.href = resp.my_redirect; to go to the new url.
If you want to redirect to other jsp page , use redirect inside controller method.
#RequestMapping("/hello")
public String hello() {
// return "powerseries";
return "redirect:powerseries";
}
// Add method to controller .
#RequestMapping("/powerseries")
public String returnPowerseries() {
return "powerseries";
}
or just use $("html").html(response); if you want to entirely change your document html.
I am using jquery to make an API call to an Entity Framework API Controller and I am trying to call the Put Method:
[ResponseType(typeof(void))]
public IHttpActionResult PutProfileIDClass(int id, ProfileIDClass profileIDClass)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != profileIDClass.id)
{
return BadRequest();
}
db.Entry(profileIDClass).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProfileIDClassExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
But when I make the API call via jQuery I get this error: 405 (Method Not Allowed)
What Am I doing wrong?
Here is my API call
var data = {
id: result.data[0].id,
profileID: result.data[0].profileID,
taken: 'true'
};
var json = JSON.stringify(data);
$.ajax({
url: '/api/ProfileIDAPI?id=' + result.data[0].id,
type: 'PUT',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
If you want to do a PUT request you should use the method: 'PUT' as part of your $.ajax call:
$.ajax({
url: '/api/ProfileIDAPI?id=' + result.data[0].id,
method: 'PUT',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
Do you have it installed on IIS? In that case, you have to configure it to handle your "PUT" request.
Right click on your website in the sidebar and go to properties.
Go to the "Home Directory" Tab
In the "applications settings", click on the "configuration" button
In the "Applications configuration" Window, there should be a Mappings Tab
Simply choose which file extensions you want to have mapped (in my case i wanted ASP to map GET, PUT, POST & DELETE), comma delimited. And thats it, not even a restart required.
Hope this helps
I'm trying to call a web service with ajax. The service is up, and it can shows the result on the RestClient on firefox, but, in mi application call, gives me Status error "Pending".
This is my simple web service.
#Controller
#RequestMapping("/hello")
public class HelloWs {
#RequestMapping(value= "/helloWorld", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public #ResponseBody String HelloWorld() {
return "Hello Worldssss¡¡";
}
And this is my ajax call.
function hellowsfunction() {
$.ajax({
type: "GET",
url:"http://localhost:8080/ehCS-ui/rest/hello/helloWorld",
crossDomain: true,
dataType: "JSON",
headers : {Accept : "applicationjson","Access-Control-Allow-Origin" : "*"},
success: function(msg) {
var returnedData = jQuery.parseJSON(msg);
$("#lblResult")
.text(result)
.slideUp("hide", function() { $(this).slideDown("slow") });
},
error: function (e) {
$("#lblResult").removeClass("loading");
alert('failed:'+e);
console.log(e);
}
});
what is wrong? Ideas?¿ please help.
Thanks
Your #RequestMapping is wrong... you should not map based on Accept header like this. Instead you should use produces parameter.
#RequestMapping(value="/helloWorld", method=RequestMethod.GET,
produces={"application/xml", "application/json"})
Also your header in the JS is incorrect. Just remove their specification completely.
I have the following ajax call which is made to my spring mvc app..
alert("ready");
$.ajax({
type: "GET",
url: document.location.toString()+ "/dashboard",
success: function(response) {
alert(response);
alert(response.status);
$("#frameBody").contents().find("html").html(response);
// we have the response
if(response.status == "SUCCESS") {
alert(response);
// do nothing..
// check for no content... if there is content... replace iframe
// $("#frameBody").attr('src', jsonObj.url);
// $(""#frameBody").contents().find("html").html(response);
}
else {
// do nothing yet
}
},
error: function(e){
$("#errors").attr("style", "display:inline")
$('#errors').html(e.responseText);
window.setTimeout("fadeErrorsDiv();", 5000);
}
});
my mvc controller:
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public String dashboard(Model model, HttpServletRequest req) {
int i = 0;
return "login";
}
My question is that i cant see why this is not producing the response status that i expect?... it gives me undefined when i check for response.status in javascript?.. any idea why
See JQuery .get docs. It would seem your "response" object inside your success callback will actually be "login". Therefore you're infact trying to do "login".status.