I work on asp.net mvc Application Ajax Request Calling.
I face Issue message sweet alert display more than once if I click button submit more than once.
If I press the same submit button again for the same request it will display (message Employee Exist Before) two times.
If I press the same submit button again for the same request it will display message validation (message Employee Exist Before) 3 times.
Correct or expected behavior
When I click submit button and employee exists before then show message validation (message Employee Exist Before) one time only.
Why that happen and how to prevent display the same message multiple times?
$("#ResignationApp").submit(function (e) {
e.preventDefault();
var formData = $(this).serialize();
console.log("data is" + formData)
$.ajax({
type: "POST",
dataType: 'json',
url: '@Url.Action("RequesterIndex", "Resignation")',
data: formData,
success: function (response) {
for (let item of response) {
if (item.Key === "success") {
success = item.Value;
}
if (item.Key === "message") {
message = item.Value;
}
}
if (success) {
Swal.fire({
icon: 'success',
title: 'Submition Request',
text: message
}).then((result) => {
if (result.isConfirmed) {
var url = '@Url.Action("IndexResignation", "Home")' + '?filenumber=' + empidval;
window.open(url, '_self');
}
});
} else {
Swal.fire({
icon: 'error',
title: 'Resignation Submission Form',
text: 'Employee Exist Before'
});
return false;
}
},
error: function (error) {
var url = '@Url.Action("UnauthorizedUser", "Home")' + '?filenumber=' + empidval;
window.open(url, '_self');
}
});
});
[HttpPost]
public JsonResult RequesterIndex(ResignationRequester resignationRequester)
{
dynamic responseData = new ExpandoObject();
responseData.success = false;
responseData.message = "";
var filenumber = resignationRequester.EmpID;
if (Session[SessionKeys.UserCode] != null)
{
JDEUtility jde = new JDEUtility();
if (ModelState.IsValid)
{
int checkEmployeeNoExist = jde.CheckEmployeeExistOrNot(resignationRequester.EmpID);
if (checkEmployeeNoExist >= 1)
{
responseData.success = false;
responseData.message = "Employee Exist Before";
return Json(responseData);
}
try
{
Workforce.InsertToReignation(resignationRequester, JoinedDate, (string)Session[SessionKeys.Username], (DateTime)Session[SessionKeys.LastWorkingDate], noticeperiod, (int)Session[SessionKeys.UserCode]);
}
catch (Exception ex)
{
responseData.success = false;
responseData.message = "Create Not Done Correctly";
return Json(responseData);
}
if (string.IsNullOrEmpty(ViewBag.errorMsg))
{
responseData.success = true;
responseData.message = "Resignation Submission form Created successfully";
return Json(responseData);
}
}
else
{
responseData.success = false;
var errors = ModelState.Select(x => x.Value.Errors)
.Where(y => y.Count > 0)
.ToList();
responseData.message = "Some Required Fields Not Added";
return Json(responseData);
}
}
else
{
responseData.success = false;
responseData.message = "No Data For This File No";
return Json(responseData);
}
return Json(responseData);
}
Updated Post
I tried solution according to your posted answer, but nothing changed.
Message still displays two additional times when I press the same button multiple times.
What I tried:
const $submitBtn = $('#btnsubmit');
$("#ResignationApp").submit(function (e) {
e.preventDefault();
// Serialize the form data
$submitBtn.prop('disabled', true);
var formData = $(this).serialize();
console.log("data is" + formData)
$.ajax({
type: "POST",
dataType: 'json',
url: '@Url.Action("RequesterIndex", "Resignation")',
data: formData,
success: function (response) {
for (let item of response) {
if (item.Key === "success") {
success = item.Value;
}
if (item.Key === "message") {
message = item.Value;
}
}
if (success) {
Swal.fire({
icon: 'success',
title: 'Submition Request',
text: message
}).then((result) => {
if (result.isConfirmed) {
var url = '@Url.Action("IndexResignation", "Home")' + '?filenumber=' + empidval;
window.open(url, '_self');
}
});
} else {
if (message === "Employee Exist Before") {
Swal.fire({
icon: 'error',
//width: '850px',
//height: '150px',
//customClass: 'swal-wide',
title: 'Resignation Submission Form',
text: 'Employee Exist Before'
});
return false;
}
else {
Swal.fire({
icon: 'error',
title: 'Resignation Submission Form',
text: message
});
return false;
}
}
console.log("errorMsg is" + errorMsg);
},
error: function (error) {
var url = '@Url.Action("UnauthorizedUser", "Home")' + '?filenumber=' + empidval;
window.open(url, '_self');
}
}).always(() => {
// re-enable the submit button...
$submitBtn.prop('disabled', false);
});
});
From the error message, it looks like your server side code is already robust enough to handle repeated requests with the same content. Therefore you simply need to update your UI to guard against the user being able to succesively click the submit button.
The simplest way to do this would be to disable the button while the AJAX request is in flight, like this:
const $submitBtn = $('#yourSubmitButton');
$("#ResignationApp").on('submit', e => {
e.preventDefault();
// disable the button when the AJAX request is sent
$submitBtn.prop('disabled', true);
$.ajax({
// ajax setup...
}).done(response => {
// 'success' handler here...
}).fail(err => {
// 'error' handler here...
}).always(() => {
// re-enable the submit button...
$submitBtn.prop('disabled', false);
});
});
Note that the button gets re-enabled in the always
handler. This is so that regardless of whether the AJAX request succeeds or fails, the button always gets re-enabled.
Also note that it would also be a good idea to show a loading spinner inside/next to the button to show that an activity is still occurring, and that the button is disabled for a purpose, rather than an error.