Ajax call always return success - javascript

I have an ajax call to my controller, which in turn calls a service which returns true or false. I cannot seem to figure out why this always triggers my success function when it returns from controller to view.
Controller
[HttpGet]
public JsonResult TagUnit(int id, string selectedItem)
{
try
{
var result = UnitClient.TagUnit(id, selectedItem);
if (!result)
{
throw new InvalidOperationException();
}
return Json(new {success = true}, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new {success = false}, JsonRequestBehavior.AllowGet);
}
}
Cshtml - Javascript - Ajax
.on("select2-selecting", function (e) {
var url = '#Url.Content("~/UnitDetails/TagUnit/" + Model.ViewUnitContract.Id)';
var id = e.val;
var tagName = e.object.text;
console.log(id + " : " + tagName);
$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function () {
alert('Success');
},
error: function () {
alert('Error');
}
});
}).select2('val', ['1', '2']);
What am I missing here?

You should validate server result data in success method.
$.ajax({
url: url,
data: { selectedItem: tagName },
type: 'GET',
dataType: 'json',
success: function (data) {
if (data != null && data.success) {
alert('Success');
} else {
alert('Error');
}
},
error: function () {
alert('Error');
}
});
Error method calls if on the server occurred 500 error or server is not avaliable, etc.

I think that if you throw an exception, it will still return with a success status code. So what I have done is create an ajax call error handler attribute that can be attached to your MVC methods. It will capture uncaught exceptions, set an error status code and give a generic error message (and also log to Elmah). The attribute is below
public class HandleJsonErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var serviceException = filterContext.Exception as Exception;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
Data = new
{
errorMessage = "Generic error message",
errorType = 0
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
var kayttaja = (Kayttaja.TKayttajantiedot)filterContext.HttpContext.Session["userKayttajanTiedot"];
Global.HandleApplicationError(serviceException, kayttaja);
filterContext.ExceptionHandled = true;
// Log to elmah
//Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);
}
}
Then decorate your action methods that should only be called by Ajax with: [Campus.Attribuutit.HandleJsonError]
The important line for triggering the error handler in the ajax call object is HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError

Don't know if I understand your question properly.
success function in Ajax will execute if the request is successful. And error function will execute if the request fails. You have to check what the server returns inside of the success function.
http://api.jquery.com/jQuery.ajax/

Related

AJAX Callback Not Showing Success Message - ASP.NET MVC C#

I have some AJAX code in my JavaScript which is not showing any success or failure alert.
function AttemptHouseViewingAppointment(house) {
var imgOfHouse = $(house).attr("value");
$.ajax({
type: "POST",
url: '#Url.Action("AttemptHouseViewingAppointment", "Viewing")',
dataType: "json",
data: ({
userId: #Model.UserId,
appointmentKey: '#Model.Key',
chosenHouse: imgOfHouse
}),
success: function (data) {
alert(data);
if (data.success) {
alert(data.message);
} else { alert(data.Message) }
},
error: function (xhr) {
alert(xhr.responseText);
}
});
};
The above function is called when I click an image on the screen. This part works fine as I have set a breakpoint on my ASP controller and I can see the relevant action being called. C# code below:
public ActionResult AttemptHouseViewingAppointment(int userId, string appointmentKey, int chosenHouse)
{
string selecteHouseName = $"./house-code-icons/{chosenHouse}.png";
var house =
_ctx.houses.Where(x => x.HouseID == userId && x.Icon == chosenHouse)
.FirstOrDefault() ?? null;
if(house != null)
{
var member = _ctx.User.FirstOrDefault(x => x.Id.Equals(userId));
_ctx.Appointments.Add(new ViewingModel
{
House = chosenHouse,
UserId = userId
});
_ctx.SaveChanges();
return Json(new { success = true, message = "Appointment Confirmed!" });
}
else
{
return Json(new { success = false, message = "Sorry, a booking has already been made!" });
}
}
Even though, the return Json lines are being hit and returned to the page, there is no alert popup on my page to let user know if success or not. Please let me know if any questions.
Thanks
Add the done function to the end of Ajax
$.ajax({
.
.
.
}).done(function( response ) {
alert(response);
...
});

How to pass a list from spring controller to ajax in jquery

This is my Jquery! Here i am not getting success response, instead a error response is thrown when a list is returned from controller to below jquery. Please let me know where i am going wrong.
//ajax method to retrieve the data from controller where controller returns list
function doAjaxPost() {
// get the form values
var pid = $('#pid').val();
$.ajax({
type: "GET",
url: "http://localhost:8085/HMS/iochart1.html",
data: "pid=" + pid,
success: function (response) {
alert(response.list4);
$.each(response, function (index, datec) {
alert(datec.name); //to print name of employee
});
},
// Even though controller returns the list,but i am not getting the above success response,instead below error method is executed.
error: function (e) {
alert('Error: ' + e);
}
});
}
Below is the controller which returns the list.
#RequestMapping(value="/iochart1", method = RequestMethod.GET)
public #ResponseBody List<Iochart> iochart1(#ModelAttribute("s") Iochart s) {
System.out.println("Patient"+s.getPid());
List<Iochart> list4 = dao.getPatientdet1(s.getPid());
return list4;
}
getPatientdet1() which retrieves the data from database
public List<Iochart> getPatientdet1(String pid) {
// TODO Auto-generated method stub
System.out.println(pid);
return template.query(
"select pid,name,fileno,age,gender,date,wardno,doctord,doctsig,ratef,nursesig,time,type,amount,typecommence,amtgiv,urine,vomitus,remarks from iochart where pid='"+pid+"'",
new RowMapper<Iochart>() {
public Iochart mapRow(ResultSet rs, int row) throws SQLException {
Iochart i = new Iochart();
i.setPid(rs.getString(1));
i.setName(rs.getString(2));
i.setFileno(rs.getString(3));
i.setAge(rs.getString(4));
i.setGender(rs.getString(5));
i.setAdmdate(rs.getString(6));
i.setWardno(rs.getString(7));
i.setDoctord(rs.getString(8));
i.setDoctsig(rs.getString(9));
i.setRatef(rs.getString(10));
i.setNursesig(rs.getString(11));
i.setTime(rs.getString(12));
i.setOraltype(rs.getString(13));
i.setOralamt(rs.getString(14));
i.setOralcommence(rs.getString(15));
i.setAmtgiv(rs.getString(16));
i.setUrine(rs.getString(17));
i.setVomitus(rs.getString(18));
i.setRemarks(rs.getString(19));
System.out.println(rs.getString(2));
return i;
}
}
);
}
Change your controller method like so. Mind the #RequestParam that is used to get the pid
#RequestMapping(value="/iochart1", method = RequestMethod.GET)
public #ResponseBody List<Iochart> iochart1(#RequestParam(name = "pid") String pid) {
return dao.getPatientdet1(pid);
}
And your ajax url like so
function doAjaxPost() {
// get the form values
var pid = $('#pid').val();
$.ajax({
type: "GET",
url: "http://localhost:8085/HMS/iochart1", //Don't postfix .hmtl
data: "pid=" + pid,
...
});
}

Implement Onfailure in webApi controller

I have a Web Api in which I have this code
#{
AjaxOptions addAjaxOpts = new AjaxOptions
{
// options will go here
OnSuccess = "getData",
OnFailure="selectView('add')",
HttpMethod = "Post",
Url = "/api/AccountManage/CreateAccount"
};
}
In the controller :
[HttpPost]
public void CreateAccount(CollaborateurModel item)
{
try{}
catch{
// return failure
}
}
I need to implement failure part to execute OnFailure method .
So how can I accomplish this task?
You can start by using Json Result (MSDN ref.)
Snippet example:
[HttpPost]
public ActionResult CreateAccount(CollaborateurModel item)()
{
try{
//do operations that may fail
var response = new { Success = true};
return Json(response );
}catch{
var errorResponse= new { Success = false, ErrorMessage = "error"};
return Json(errorResponse);
}
}
Then on the client side you call the controller using JQuery:
$(function () {
$(".test-link").click(function (e) {
$.post("controllerName/CreateAccount", function (data) {
if (data.Success == true) {
alert("Success");
}
else {alert(data.ErrorMessage);}
});
return false;
}).fail(function() {
alert( "error" );
});
});
The fail function on Jquery will handle communication problems that you may have with client-server.
More info about JQuery you can find it here.
Depending on your desired response status code, you can use the BadRequest, NotFound or InternalServerError result classes. Each of these have a constructor that has an optional parameter for an error message.
[HttpPost]
public IHttpActionResult CreateAccount(CollaborateurModel item)
{
try
{
// Do your thing
}
catch
{
// Return a HTTP 400 result
return BadRequest("This is an error message");
}
}

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.

Categories

Resources