AJAX call in external JavaScript file not reaching ActionResult in controller - javascript

I am trying to check if an email address exists in the database. I have an external JavaScript file that I am using to call my jQuery (to keep my view clean). Perhaps it is because I am running with SSL enabled? (I am using https)
Function in external js file:
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists/",
data: JSON.stringify({ p: email }),
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data)
}
});
}
Action in Controller:
public ActionResult CheckEmailExists(string p)
{
bool bEmailExists = false;
using (RBotEntities EF = new RBotEntities())
{
var query = (from U in EF.AspNetUsers
where U.Email == p
select U).FirstOrDefault();
if(query.Email != null)
{
bEmailExists = true;
}
else
{
bEmailExists = false;
}
}
return Json(bEmailExists, JsonRequestBehavior.AllowGet);
}
I seem to be getting an error stating the following:
XML Parsing Error: no root element found Location:
https://localhost:44347/Account/CheckEmailExists/ Line Number 1,
Column 1:
My understanding would be that this ActionResult does not exist. But it does ?
Am I doing something wrong, or is there a reason why an ActionResult can not be called via an external JavaScript file ?

Try this
In Controller
[httppost]
public ActionResult CheckEma.........
In JS
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists/",
data: { p: email },
type: "POST",
success: function (data) {
alert(data)
}
});
}

No need for Json.Stringify and ContentType here
function checkemail() {
var email = $("#email").val();
$.ajax({
url: "/Account/CheckEmailExists",
data: { p: email },
type: "POST",
success: function (data) {
alert(data)
}
});
}

So I found out what was causing the issue...
Above my Action result, I needed to add [AllowAnonymous] data annotation and then it reached my ActionResult! I would prefer to not allow anonymous, but it works and I wanted to share this in case it helps someone else. Below is my code:
ActionResult:
[AllowAnonymous]
public ActionResult CheckEmailExists(string p)
{
bool bEmailExists = false;
using (RBotEntities EF = new RBotEntities())
{
var query = (from U in EF.AspNetUsers
where U.Email == p
select U).FirstOrDefault();
if (query.Email != null)
{
bEmailExists = true;
}
else
{
bEmailExists = false;
}
}
return Json(bEmailExists, JsonRequestBehavior.AllowGet);
}
JavaScript function in JavaScript File:
function checkemail() {
var email = $("#email").val();
var bReturnedValue = false;
$.ajax({
url: "/Account/CheckEmailExists/",
data: { p: email },
async: false,
success: function (data) {
if(data)
{
bReturnedValue = true;
}
else
{
bReturnedValue = false;
}
}
});
return bReturnedValue;
}
And this is how I initiated it(I am doing a popover to specify that the email exists):
$("#createacc_next").click(function () {
var bEmailExists = false;
bEmailExists = checkemail();
if (bEmailExists) {
$("#email").attr("disabled", false).css("border-color", "red");
$('#email').popover({ title: 'Attention', content: 'Email address already exists', placement: 'top', trigger: 'focus' });
Email_Validation_Passed = false;
}
})

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

NotifyJS works on one function and not the other even when the code it's exactly the same

I have a form that returns a message whether a new value it's added or deleted, this alert returns a message at the top of the screen only on the modify function but not on the submit one, the code it's exactly the same both the JS call and the C# side.
The JS its like this:
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
var archivo = document.getElementById("FileUpload").Value;
form.append("FileUpload", archivo);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
$('#table').DataTable().ajax.reload()
/*NOTIFY ON ADD NOT WORKING*/
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
function Modify(id) {
if(confirm('You sure you want to modify this record'))
{
$.ajax({
type: "POST",
url: '#Url.Action("Modify","Custom")/' + id,
success: function (data) {
if (data.success)
{
$('#table').DataTable().ajax.reload()
/*NOTIFY ON MODIFY WORKING*/
$.notify(data.message, {
globalPosition: "top center",
className: "error"
})
}
}
});
}
}
And the C# side of both classes:
[HttpPost]
public ActionResult Add(addLic lic, string FileUpload)
{
using (Entities1 db = new Entities1())
{
//DO INSERT STUFF
db.SaveChanges();
return Json(new { success = true, message = "Registro guardado exitosamente." }, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public ActionResult Modify(int id)
{
using (Enitities1 db = new Entities1())
{
//DO UPDATE STUFF
db.Entry(lic).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return Json(new { success = true, message = "Registros modificados correctamente." }, JsonRequestBehavior.AllowGet);
}
}
Am I running Notify.JS the wrong way on the add notification? Can I call it other way?

ASP.NET MVC Ajax submit form with AntiforgeryToken and Serialized Form data with Validation

I am trying to submit a form via ajax like this:
$(document).ready(function () {
$("#form").submit(function (e) {
e.preventDefault();
var token = $('input[name="__RequestVerificationToken"]', this).val();
var form_data = $(this).serialize();
$.ajax({
url: "#Url.Action("SaveRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: form_data,
contentType: "application/json",
success: function (result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
return false;
console.log(form_data);
});
});
This contacts this controller:
[HttpPost]
[ValidateAjax]
[ValidateAntiForgeryToken]
public ActionResult SaveRole(SaveRolesDetailsViewModel Input)
{
//var role = rolesData.GetByName(Input);
var result = this.Json(new
{
Output = Input
}, JsonRequestBehavior.DenyGet);
return result;
}
Right now, I'm getting errors that my RequestVerificationToken field is not being submitted but I'm not sure how I can combine it with my form data. By default, when I serialize my form data, it already sends this token but for some reason my controller still fails it.
Also, how do I use the modelstates to show my form validations? Right now they are returned as json objects.
EDIT:
AjaxValidate Attribute:
public class ValidateAjax : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
}
When I submit an empty form, this is what is returned:
0:{key: "RoleName", errors: ["The Role Name field is required."]}
When you use the jQuery .serialize() method, it generates query string format (i.e. ..&name=value&..., which needs to be sent using the default contentType - i.e 'application/x-www-form-urlencoded; charset=UTF-8'.
Remove the contentType: "application/json", from the ajax options.
In addition, your var token = $('input[name="__RequestVerificationToken"]', this).val(); line of code is not necessary - the token is included when you use .serialize()
$("#form").submit(function (e) {
e.preventDefault();
// Add the following if you have enabled client side validation
if (!$(this).valid()) {
return;
}
var form_data = $(this).serialize();
$.ajax({
url: "#Url.Action("SaveRole")",
method: "POST",
data: form_data,
success: function (result) {
... // see notes below
},
error: function (error) {
console.log(error);
}
});
// return false; not necessary since you have used e.preventDefault()
console.log(form_data);
});
To return ModelState errors, remove your ValidateAjaxAttribute - returning a BadRequest is not appropriate (which is intended to indicate that the server could not understand the request due to invalid syntax).
Instead modify the POST method to return a JsonResult that includes the errors (note there is no need to return the model)
public ActionResult SaveRole(SaveRolesDetailsViewModel Input)
{
if (ModelState.IsValid)
{
return Json(new { success = true });
}
else
{
var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });
return Json(new { success = false, errors = errors });
}
}
Then in the success callback, if there are errors, loop through them and find the corresponding <span> element generated by your #Html.ValidationMessageFor() and update its contents and class names
success: function (result) {
if (result.success) {
return;
}
$.each(result.errors, function(index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
},

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.

Categories

Resources