No response status in ajax call not sure why - javascript

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.

Related

Ajax always executes error function on success with Asp.Net HttpResponseMessage

When I send my Ajax request I can see that the returned status code is 200 which means everything worked fine. However, it always executes the error function instead of the success function.
Web Api
public HttpResponseMessage ChangeModus(Artikel Artikel)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
JavaScript
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: "/Api/Artikel/ChangeModus",
data: JSON.stringify(Artikel),
success: OnSaveSuccess,
error: OnSaveError
});
function OnSaveSuccess(response) {
alert("Success")
}
function OnSaveError(response) {
alert("Ein Fehler ist aufgetreten");
}
Am I doing something wrong or why does it always execute the Error function?
The error is occurring because although you have a 200 (OK) response, the response does not include a response body. You should either send content with the response, or use HttpStatusCode.NoContent (204) instead.
Like Jakob said, the problem occurs because there has to be a response body otherwise javascript will execute the error function.
Choose one of the following options:
public HttpResponseMessage ChangeModus(Artikel Artikel)
{
return Request.CreateResponse(HttpStatusCode.OK, "Success");
}
Or:
public HttpResponseMessage ChangeModus(Artikel Artikel)
{
return Request.CreateResponse(HttpStatusCode.NoContent);
}

Redicrect in Spring MVC

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.

How to return data from controller method to a jquery ajax post

My Jquery ajax call -
var formdata = $('#emailrequest').serializeArray();
// Ajax call to server
$.ajax({
url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
type: 'POST',
data: formdata,
sucess: function(data) {
alert(data.sucess);
},
error: function() {
alert('error');
}
});//End Ajax
My controller -
public ActionResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new {success = true});
But all is get is error in alert . Where am I going wrong? Please help . I just need to return a confimation from controller , be it any format.
You spelled success wrong so it will never hit. It should work with the ActionResult but a JsonResult is better.
var formdata = $('#emailrequest').serializeArray();
// Ajax call to server
$.ajax({
url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
type: 'POST',
data: formdata,
success: function(data) {
alert(data.sucess);
},
error: function() {
alert('error');
}
});//End Ajax
Try to set your controller method return type to JsonResult instead of ActionResult, so:
public JsonResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new {success = true});
}
If that doesn't help set your ajax error function to receive following parameters:
error: function (xhr, ajaxOptions, thrownError) {
...
}
Then debug in browser and set a break point to error function and in the xhr object (responseText property) you'll be able to see exact error.
you shoudn't return json like that. use [ ] instead of {}
public JsonResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new [success = true]);
}

.NET MVC JSON Post Call response does not hit complete or success

I am new to .NET MVC so please bear with me.
I wrote a function that gets triggered when there is a blur action on the textarea control:
function extractURLInfo(url) {
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
complete: function (data) {
alert(data);
},
success: function (data) {
alert(data);
},
async: true
})
.done(function (r) {
$("#url-extracts").html(r);
});
}
jQuery(document).ready(function ($) {
$("#input-post-url").blur(function () {
extractURLInfo(this.value);
});
});
This works fine and will hit the controller:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
I get the intended results if the URL is valid; it will return a partialview to the .done() function and I just display it in code. However, if the URL is not valid i want it to hit either complete, success, or done (I have been playing around to see which it will hit but no luck!) and do something with the returned data. I had it at some point trigger either complete or success but the data was 'undefined'. Can someone help me out on this?
Thanks!
In both cases your controller action is returning 200 status code, so it's gonna hit your success callback:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
if (data.message) {
// Your controller action return a JSON result with an error message
// => display that message to the user
alert(data.message);
} else {
// Your controller action returned a text/html partial view
// => inject this partial to the desired portion of your DOM
$('#url-extracts').html(data);
}
}
});
But of course a much better and semantically correct approach is to set the proper status code when errors occur instead of just returning some 200 status code:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
and then in your AJAX call you would handle those cases appropriately:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
$('#url-extracts').html(data);
},
error: function(xhr) {
if (xhr.status == 400) {
// The server returned Bad Request status code
// => we could parse the JSON result
var data = JSON.parse(xhr.responseText);
// and display the error message to the user
alert(data.message);
}
}
});
Also don't forget that you have some standard way of returning your error messages you could subscribe to a global .ajaxError() handler in jQuery instead of placing this code in all your AJAX requests.

Web service Spring ajax call

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.

Categories

Resources