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

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.

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

Ajax callback is firing after function call

Hi Have a ajax call in a function thats called on date input change event to check if a date is already in use for User. the success in the Ajax call fires after the click function is finished.
How do I get the success results and continue on with the #datepicker change funtion as I need the json results for rest of function.
controller
public ActionResult IsDateAvailable(DateTime date, int Id) {
var dateAvailable = !(_context.Trading.Any(t => t.uId == Id && t.TradingDate == date));
if (!(dateAvailable)) {
return Json(new {
status = false, msg = "This date already exists."
});
}
return Json(new {
status = true
});
}
JavaScript
$(document).ready(function() {
var message;
var isDateValid;
function CheckDate(para) {
var dateValid;
var mesg;
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
$("#datePicker").change(function() {
$("#alert").css({
'display': 'none'
});
if (Id == 0) {
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text('Please select a User.');
$("#alert").show();
return false;
}
var date = $(this).val();
var para = {
date: date,
Id: Id
};
CheckDate(para);
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
});
});
You should turn to being asynchronous. change your code to match with these:
.
.
.
function CheckDate(para) {
return new Promise((resolve, reject) => {
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
resolve();
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
reject();
}
});
}
.
.
.
checkDate(para).then(res => {
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
}).catch(err => { /* do something */ });
You just need to set async: false inside your ajax request. You can also remove the word return from the CheckDate, because of it's redundant:
function CheckDate(para) {
var dateValid;
var mesg;
$.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
async: false,
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}

Delete record by using ajax from database EntityFramework

I am beginner and trying to delete the record from database by using JavaScript, Ajax and Json in MVC Entity Framework. But my delete button is not working well.
In controller class my action code is
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
and my JavaScript code is
<button id='deleteRecord'>delete</button>
$("#deleteRecord").click(function () {
var StudentId = $(this).val();
var stdId = parseInt(StudentId);
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I shall be very thankful if anybody help me.
You need to add your model id in jquery data tag:
<button id='deleteRecord' data-model-id="#model.Id">delete</button>
Then in javascript code:
$("#deleteRecord").click(function () {
var StudentId = $(this).data("model-id");
var url = "/AjaxStudent/Delete/" + StudentId;
$.ajax({
url: url,
type: 'Delete',
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I think that the error comes from the type attribute of your ajax call. You assign "delete" to this attribute, but it must be "POST":
$.ajax({
url: "#Url.Action("Delete","AjaxStudent")",
type: "POST", // here is your problem,
data: { StudentId: stdId },
dataType: 'json',
success: function() {
alert("Deleted");
},
error: function(dat) {
alert(data.x);
}
});
And the action method in your controller must be decorated with [httppost] :
[HttpPost]
public JsonResult Delete(int StudentId)
{
using (StudentContext db = new StudentContext())
{
Student std = db.Student.Where(x => x.Id == StudentId).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
you should try by changing :
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
to:
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
'id':stdId
}
After lots of time I am able to resolve my problem.
Now my javaScript code
<button class='deleteRecord' data-stid=" + students[i].Id + " >delete</button>
$(".deleteRecord").click(function () {
var StudentId1 = $(this).data("stid");
debugger;
$.ajax({
url: "/AjaxStudent/Delete/" + StudentId1,
type: "Post"
}).done(function () {
getAllStudents();
});
});
});
Controller.cs
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}

AJAX call in external JavaScript file not reaching ActionResult in controller

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

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

Categories

Resources