Asp.net MVC - Jquery $.ajax error callback is not returning responseJSON
Asked Answered
G

2

11

I have the code below, with works fine on the development machine but not when called from a remote browser...

$.ajax({
  type: 'POST',
  url: '@Url.Action("Action", "Controller")',
  data: { id: id },
  dataType: 'json',
  async: true,
  success: function (data) {
  },
  error: function (jqXHR, status, err) {
    var result = jqXHR.responseJSON;
  }
});

The jqXHR.responseJSON object works when calling from localhost but not when the call is made from a remote computer, it's returned as undefined... Could somebody help me? Thanks in advance!

enter image description here

Gosnell answered 29/8, 2016 at 18:41 Comment(3)
What do you get back in jqXHR instead?Costumer
Hi Jasen, thanks for reply! In the development machine, it returns a responseJSON array correctly as well as a reponseText with the json string, but when it's called from a remote machine, the responseJSON object doesn't exists, returning null, and responseText only contains "Bad request message" as i've signed the response status code as 400. I've edited the question with a picture of the result...Gosnell
Do you have any error in console? Does it has something to do with CORS? Anything in console like "Access-Control -Origin...."Elviselvish
T
14

I have been having sort of the same issue. When testing on my local machine using localhost, the ResponseJSON is filled. When I upload my project to the test server and test, my responseJSON is undefined and the responseTEXT is just giving the statusdescription that I sent:
(this is a JSONResult but I've done it as ActionResult)

Response.StatusCode = 400;
Response.StatusDescription = "Bad Request - Model State is Invalid";
return Json(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ModelState.Values.SelectMany(v => v.Errors)), JsonRequestBehavior.AllowGet);

and for ActionResult specifically I also tried:

return new HttpStatusCodeResult(400, new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ModelState.Values.SelectMany(v => v.Errors)));

which gave me a bunch of errors.

I tried with JsonResult the following code, which WORKED locally (but I had a syntax error in the JSON) but did not work on the test server.

return Json(new { success = false, responseJSON = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ModelState.Values.SelectMany(v => v.Errors)) }, JsonRequestBehavior.AllowGet);

This is a recent test (above) when I used an AJAX request to submit a form model to an MVC Controller. I read that it's because it's going cross-domain but that makes no sense.

I created a web API controller and put the method information in there. This is because I wanted to use HttpReponseMessage and i figured that was a WebAPI type. After getting the model and the json and everything to work together, I tested and guess what?

When i use the HttpResponseMessage as the return type in WebAPI and return like this:

return Request.CreateResponse(HttpStatusCode.BadRequest, new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ModelState.Values.SelectMany(v => v.Errors)));

The responseJSON and responseText both fill correctly.

I don't know why it doesn't work otherwise and if someone has a response for that please tell us.

To me this is a work around because I feel like it should've worked the first way.

UPDATE: Using the ORIGINAL code with the MVC Controller- and adding

Response.TrySkipIisCustomErrors = true;

made the responseJSON appear.

Tabbie answered 29/8, 2016 at 20:16 Comment(4)
Yeah that's all strange! I'll try your solution to see if it works with mvc projects... Thanks a lot!Gosnell
@JuniorSilva using Request.TrySkipIisCustomerErrors = true; worked with ActionResult on the MVC controller returning Json(Serializing model errors, AllowGet);Tabbie
Yeah! It works like a charming... Thanks a lot guys, saved my life!Gosnell
you really saved my day. @TabbieOrvil
K
2

As suggested by nebulous, Response.TrySkipIisCustomErrors = true; seems to be the right way.

Unfortunately, most of the time IIS will ignore this property, and skip it (maybe that's why the developers call it Try...).

However, I fixed the trouble adding this on the Web.config:

<system.webServer>
  <httpErrors existingResponse="PassThrough" />
</system.webServer>

which is cleaner and doesn't "dirty" the code part.

Hope it helps.

Kirk answered 24/7, 2018 at 7:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.