jQuery AJAX always executing error: {} - c#

I'm working on a webapplication, ASP.Net MVC 4.0 with entityframework 6.0, trying to update database as per user selection. Data is sent to controller's action using jQuery AJAX. Below given is C# code to update entity which in turn updates database.
public void modidyProduct(Productdetail prodData)
{
try
{
using (SampleTrialEntities entity = new SampleTrialEntities())
{
var data = entity.Productdetails.Where(p=>p.ProductID == prodData.ProductID).FirstOrDefault<Productdetail>();
data.ProductName = prodData.ProductName;
data.ProductNumber = prodData.ProductNumber;
data.CategoryName = prodData.CategoryName;
data.ModelName = prodData.ModelName;
entity.Entry(data).State = System.Data.Entity.EntityState.Modified;
entity.SaveChanges();
}
}
catch (Exception)
{}
}
And here's jQuery AJAX call for that controller action method.
function updateProduct() {
var productData = {
ProductName: $('#prodName').val().trim(),
ProductNumber: $('#prodNum').val().trim(),
CategoryName: $('#ctgryName :selected').text(),
ModelName: $('#mdlName :selected').text(),
ProductID: atob($('#editProductId').val())
};
debugger;
$('#divLoader').show();
$.ajax({
url: '#Url.Action("modidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
success: function (jqXHR) {
//Below line will destroy DataTable - tblProducts. So that we could bind table again. next line - loadData();
$('#tblProducts').DataTable().destroy();
$('#divLoader').hide();
loadData();
$('#addModal').modal('hide');
$('#editProductId').val('');
},
error: function (msg) {
debugger;
$('#editProductId').val('');
$('#divLoader').hide();
alert(msg);
alert("What's going wrong ?");
//alert(jqXHR.responseText);
}
});
}
After executing jQuery AJAX method & controllers action, successfully updates the record in database. Response statuscode - 200 & Status - OK is returned. But only error: { }, code block is executed every time in AJAX method.
Debugging screen capture with status-OK; statuscode - 200

This part of your $.ajax method call
dataType: 'json',
It tells jQuery that, the ajax call code is expecting a valid JSON response back but currently your server method's return type is void. That means it won't return anything and the $.ajax method is trying to parse the response (assuming it is a valid JSON), and hence getting the typical "parsererror"
When the datatype is json and the response is received from the server, the data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected.
The solution is to simply remove the dataType property in the call.
$.ajax({
url: '#Url.Action("modidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
contentType: 'application/json;charset=utf-8'
}).done(function() {
console.log('Success');
})
.fail(function(e, s, t) {
console.log('Failed');
});
Or you can update your server action method to return a json response.
[HttpPost]
public ActionResult ModidyProduct(Productdetail prodData)
{
try
{
//to do : Save
}
catch (Exception ex)
{
//to do : Log the exception
return Json(new { status = "error", message=ex.Message });
}
return Json(new { status="success"});
}
Now in your client side code, you can check the json response to see if the transaction was successful
$.ajax({
url: '#Url.Action("ModidyProduct", "Home")',
data: JSON.stringify(productData),
type: 'POST',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
}).done(function (res) {
if (res.status === 'success') {
alert('success');
} else {
alert(res.message);
}
console.log('Success');
}).fail(function(e, s, t) {
console.log('Failed');
});
You do not need to necessarily specify the dataType property value. If nothing is specified jQuery will try to infer it based on the mime type of the response coming back, in this case, the response content type will be application/json; charset=utf-8. So you should be good.

Related

No errors on backend, but Ajax function is failing

I have an Ajax Call and a Controller with some methods and there is something weird.
The Ajax call can reach the Controller Method. The method is returning the value perfectly, no errors, nothing. However, in the AJAX the return is coming with error (not on success of Ajax).
Moreover, If I inspect the return I can see the correct values on responseJson, but the status is 404 and statusText is "error" ({"readyState":4,"status":404,"statusText":"error"})
Anyone have an idea what is going on? There is no error in backend, however error in Ajax.
Controller Method
public JsonResult SceneListUpdated(string sceneId)
{
SceneListModel model = new SceneListModel();
var licenseValidationState = KeygenLicenseState.CheckLicense();
if (licenseValidationState == 0)
{
SceneListService sceneService = new SceneListService();
model = sceneService.GetSceneListUpdated(sceneId);
return Json(new { Success = true, data = model }, JsonRequestBehavior.AllowGet );
}
return Json(new { Success = false, data = "" }, JsonRequestBehavior.AllowGet);
}
Ajax Function
$.ajax({
url: "/api/test/SceneList/SceneListUpdated?sceneId=" + sceneIdAux, //Method in controller
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (e) {
},
error: function (data) {
}
});
try to fix the ajax
$.ajax({
url: "/api/test/SceneList/SceneListUpdated/"+ sceneIdAux, //Method in controller
type: "GET",
success: function (e) {
},
error: function (data) {
}
});
and maybe you can try one of these routing since you have 404
[Route("{sceneId}")]
[Route("~/api/SceneList/SceneListUpdated/{sceneId}")]
public JsonResult SceneListUpdated(string sceneId)

ajax POST sending null

I originally wrote the call as a GET but found a limitation with the length of the URI. Ideally, the call will take an object and turns it into a JSON format string, then sends it to a controller which will encrypt that string. The controller will send back a true/false if it succeeded.
My problem with POST, once it reaches the controller, the data parameter set from the ajax is null.
Here is the ajax/js:
var encActionURL = '#Url.Action("Encrypt", "Home")';
$.ajax({
url: encActionURL,
type: "POST",
contentType: "application/json; charset=utf-8;",
dataType: "json",
async: true,
traditional: true,
data: { jsonDoc: JSON.stringify(jsonDataFile) },
success: /*OnSuccess*/ function (result) {
// DO STUFF;
}
});
Here is the controller:
[HttpPost]
public bool Encrypt(string jsonDoc)
{
return serverConnection.Encrypt();
}
Note that, when I simply change the type to 'GET', it works great but when the form gets too long, it throws a 414 status error.
Most of the fixes found that I seem to have is the 'application/json'. I've also set ajax to traditional.
After going through a rabbit-hole of security tokens and validating forms, it wasn't any of that... this might be a solution for anyone using ASP.NET Core 2.1 MVC (5?) or just in general. Could have been a syntax mistake, return type mistake, or a combination.
New Ajax
$.ajax({
url: encActionURL,
type: "POST",
data: { 'jsonDoc': JSON.stringify(jsonDataFile) }, // NOTICE the single quotes on jsonDoc
cache: false,
success: /*OnSuccess*/ function (result) {
// DO STUFF;
}
});
New Controller
[HttpPost]
public ActionResult EncryptJSON(string jsonDoc) // Switch to ActionResult, formerly JsonResult
{
return Json(serverConnection.Encrypt());
}

How to get value from controller back to $.Ajax

My setup: asp.net mvc web app
I am having trouble getting a value from a controller back to the $.Ajax call (see below). The controller deletes a record in a database and counts some other records.
$.ajax({
type: "POST",
url: actions.action.RemoveItem + "?id=" + dataId,
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
success: function (result) {
alert(result);
},
error: function (result) {
alert("Error");
}});
[HttpPost]
public JsonResult RemoveItem(int id)
{
... delete a record in the db
itemsCount = .... counts of some other records in the db
if (deletedRecord.id != null)
{
return Json(new { itemsCount });
}
else
{
return JsonError();
}
}
The ajax call and the controller work properly, however when I try to use the returned value in the success function, the alert(result) gives [object object].
I have looked through all related posts, but could not find a solution that worked. Could someone give me a hint where the problem could be and how to make it work?
Thank you in advance and regards, Manu
Result is a javascript object so alert works properly. If you want to alert it's structure as JSON use JSON.stringify() method like this:
alert(JSON.stringify(result));
If you want to access your itemsCount, just use dot or bracket notation:
alert(result.itemsCount);
alert(result['itemsCount']);

getting data from controller in error function of jquery ajax -- Asp.net MVC

I have a jquery ajax script like following
$.ajax({
type: "POST",
url: "Main/receive", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'p':$("#txtname").val() }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
// Or if you are returning something
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
And I am calling to Controller action method. The data is sending to the controller's action method and I am also receiving data from the controller. But the data that I am receiving is inside the error function of jquery ajax.
I want it to be inside the success function.
Why my success function is not getting called.
Following is my controller's action method,
[HttpPost]
public string receive(string p)
{
ViewBag.name = p;
return p;
}
The reason for the error is that you have specified that the returned data type be json (in the line dataType: "json",) but you method returns text. You have 2 options.
Change the controller method to return json using return Json(p);
Change the ajax option to dataType: "text", or just omit it
However you can improve your script as noted below
$.ajax({
type: "POST",
url: '#Url.Action("receive", "Main")', // don't hardcode url's
data: { p: $("#txtname").val() }, // no need to stringify (delete the contentType: option)
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
or even simpler
$.post('#Url.Action("receive", "Main")', { p: $("#txtname").val() }, function(result) {
alert('Yay! It worked!');
}).fail(function(result) {
alert('Oh no zzzz:('+result.responseText);
});
Notes: You should always use #Url.Action() to generate the correct urls, and it is not necessary in this case to stringify the data (but you need to remove the contentType: line so it used the default application/x-www-form-urlencoded; charset=UTF-8)
In addition, this is not strictly a POST (your not changing data on the server - but I assume this is just for testing). And there is no point in the line ViewBag.name = p; - it does nothing in your context, and as soon as you return from the method, ViewBag is lost anyway.
try to change your controller code as follows
[HttpPost]
public ActionResult List(string p)
{
ViewBag.name = p;
return Json(ViewBag);
}
Your controller method should look like this:
[HttpPost]
public ActionResult receive(string p)
{
return Json(p);
}

Properly displaying ajax error.responseText

I want to display in a webpage an exception message raised in my .NET code in the error part of an ajax request:
[HttpPost]
[AllowAnonymous]
public virtual ActionResult AuthenticateUser(string somedata)
{
throw new Exception("Ooops!!");
}
JS code:
jQuery(document).ready(function () {
jQuery.ajax(
'#Url.Action("AuthenticateUser")',
{
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
somedata:somedata
},
success: function (result) {
if (result == 'true') {
window.location = '#Url.Content(Request["returnUrl"])';
}
},
error: function (response) {
var responseJson = jQuery.parseJSON(response.responseText);
$('#errorMessage').text(responseJson.Message);
$('#progress_message').text("");
},
type: 'post'
}
);
});
The error I get in "response" is HTML code and I want to parse it to get the exception message I throw from the server side. So, the better approach I came up with was to return a Json response, but despite specifying "json" as datatype I still receive HTML code in "response", so... what am I doing wrong? Is the problem the "Exception" object I throw from the server side?
The problem is that whenever an exception is thrown in a controller, it will always trigger asp.net's error page and return whatever is configured for the 500 http status code (the default result is the "yellow page of death" which is an html), what you are trying to do is custom error handling and there are several ways of doing it in depth explanation is present in this blog
One way you could do this is by overriding the OnException method:
protected override void OnException(ExceptionContext filterContext)
{
filterContext.Result = Json(new {Message = filterContext.Exception.Message});
filterContext.ExceptionHandled = true;
}
This will replace the default result for an internal server error (500) with a json result containing the error message, which can be obtained like below
jQuery.ajax(
'#Url.Action("AuthenticateUser")',
{
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (response) {
var responseJson = jQuery.parseJSON(response.responseText);
console.log(responseJson.Message); //Logs the exception message
},
type: 'post'
});
This will catch errors Controller wise, if you want to do this application wise you will have to go a little deeper on the blog's methods (probably with the "HandleError" Attribute)
In the end I returned JsonResults and handled the message from the view:
Server code:
[HttpPost]
[AllowAnonymous]
public virtual JsonResult AuthenticateUser(string somedata)
{
if (ok)
return new JsonResult() {Data="ok"}
return new JsonResult() {Data= "Missing data blah"}
}
And in javascript:
success: function (result) {
if (result == 'ok') {
window.location = '#Url.Content(Request["returnUrl"])';
return;
}
$('#progress_message').text("");
$('#errorMessage').text(result);
},

Categories

Resources