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

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);
...
});

Related

Why Ajax edit code not work properly? can you help me?

I m working on simple registration i have two forms one is registration another is city, When city is newly added it get added update perfectly but when i use city in registration form eg pune. pune will not get edited or updated, code written in ajax
function UpdateCity(Ids) {
debugger;
var Id = { Id: Ids }
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
}
})
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
}
debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
dataType: "text",
success: function (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
window.setTimeout(function () { location.reload() }, 3000)
}
})
})
}
Controller
public bool UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
return true;
}
catch (Exception Ex)
{
return false;
}
}
A few stabs in the dark here but, try changing your code to the following (with comments).
Controller:
// !! This is a POST transaction from ajax
[HttpPost]
// !! This should return something to ajax call
public JsonResult UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
// !! Change return type to Json
return Json(true);
}
catch (Exception Ex)
{
// !! Change return type to Json
return Json(false);
}
}
Script:
function UpdateCity(Ids) {
//debugger;
var Id = { Id: Ids };
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/GetCityDetail");
}
});
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
};
//debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
// !! Change return type to Json (return type from Server)
dataType: "json",
success: function (city) {
// !! Check result from server
if (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
// !! Why reload location?
// window.setTimeout(function () { location.reload(); }, 3000);
} else{
// !! Change this to something more suitable
alert("Server Error: /City/UpdateCity");
}
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/UpdateCity");
}
});
});
}
This should give you some more clues as to what's going on.

ASP.NET MVC call Controller Action with parameter from javascript function

I have web application in ASP.NET MVC C#. I want to call Controller Action method with parameters from javascript but I get always null for parameters.
In .js I have:
$.ajax({
cache: false,
url: this.saveUrl,
type: 'post',
success: this.nextStep,
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
nextStep: function (response) {
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
if (response.redirect) {
ConfirmOrder.isSuccess = true;
location.href = response.redirect;
return;
}
if (response.success) {
ConfirmOrder.isSuccess = true;
window.location = ConfirmOrder.successUrl;
//window.location.href = #Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
//window.location.href = '#Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
}
Checkout.setStepResponse(response);
}
in RouteProvider.cs I have:
routes.MapLocalizedRoute("CheckoutCompleted",
"checkout/completed/{orderId}/{customerComment}/{customerDate}",
new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
new { orderId = #"\d+", customerComment = #"\w+", customerDate = #"\w+" },
new[] { "Nop.Web.Controllers" });
And finaly in Controller I have:
public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
{
//some code here
}
I always get parameters value null and I don't know why. I try to call this Action with parameters on several diferent way like I saw on this forum but no success.
Did you add httpPost wrapper to your controller ?
[HttpPost]
public virtual ActionResult Completed(MyClass MyClassObj )
{
//some code here
}
in your Ajax code u didn't mention your Data type And Data try This Ajax
function Save () {
try {
var req = {
DeliveryCode: value,
}
$.ajax({
url: URL,
type: 'POST',
data: req,
dataType: "json",
async: true,
success: function (result) {
resetLoadWaiting()
},
error: function (e) {
}
});
}
catch (e) {
}
}
Mistake was in url string. Correct one is
ConfirmOrder.successUrl = "http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14"
I found this solution in this answer: Routing with Multiple Parameters using ASP.NET MVC
I dont need to update RouteProvider with new parameters. It is enough to put in in Controller Action method. Other things happen automatically.

jQuery $.ajax() call is hanging and I cannot do nothing until the call ends

Hi;
when i'm using from jQuery ajax, the page getting to freeze until request end.
this is my JavaScript code:
function GetAboutContent(ID, from) {
var About = null;
if (from != true)
from = false;
$.ajax({
type: "POST",
url: "./ContentLoader.asmx/GetAboutContent",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'ID': ID, 'from': from }),
async: true,
success: function (msg) {
var Result = msg.d.Result;
if (Result == 'session') {
warning('Your session has expired, please login again!');
setTimeout(function () {
window.location.href = "Login.aspx";
}, 4000);
return;
}
if (Result == 'failed' || Result == false) {
About = false;
return;
}
About = JSON.parse(msg.d.About)[0];
}
});
return About;
}
and this is my WebService
[WebMethod(EnableSession = true)]
public object GetAboutContent(int ID, bool from = false)
{
try
{
if (HttpContext.Current.Session["MahdParent"] != null ||
HttpContext.Current.Session["MahdTeacher"] != null ||
from)
{
functions = new GlobalFunctions();
DataTable queryResult = new DataTable();
queryResult = functions.DoReaderTextCommand("SELECT Field FROM TT WHERE ID = " + ID);
if (queryResult.Rows.Count != 0)
return new { Result = true, About = JsonConvert.SerializeObject(queryResult.Rows[0].Table) };
else
return new { Result = false };
}
else
return new { Result = "session" };
}
catch (Exception ex)
{
return new { Result = "failed", Message = ex.Message };
}
}
How can i solve that problem?
please help me
In the last line you try to return About. That cannot work due to the asynchronous nature of an AJAX request. The point at which you state return About doesn't exist any more when the success function of your AJAX request runs.
I assume you try do do somehting like this:
$('div#content').html(GetAboutContent());
In a procedural lantuage like PHP or Perl this works fine, yet JavaScript functions in a very different way. To make something like this work you'd do something like this:
$.ajax({
type: "post",
url: "./ContentLoader.asmx/GetAboutContent",
dataType: "json",
data: {
'ID': ID,
'from': from
},
success: function(result) {
$('div#content').html(result)
}
});
The difference between the two bits of code is that the first would expect JavaScript to know the value at the time you request it. However, your function GetAboutContent() doesn't have instant access to these data. Instead it fires up an AJAX request and ends right after that with the request still in progress for an unknown amount of time.
Once the request finishes successfully the data is available to JavaScript. and you can work with it in the callback function defined for success. By then the request has absolutely no connection to the function that started it. That's why it's asynchronous.

.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.

Ajax call always return success

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/

Categories

Resources