I am using kendo ui and i dont want duplicate records in my database so what i am doing is using the .Save function of kendo grid to check the record and if exist then return false which is working fine but when i am returning return false then it is still saving the record.
function onSave(e) {
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax(
{
url: '/StudentTransaction/CheckRegistrationNumber',
type: "POST",
data: { 'RegisterNumber': currentValueForSend },
success: function (data) {
alert(data.CurrentRegNo);
if( data.CurrentRegNo.indexOf('true') >= 0){
alert("no duplicate records");
return false;;
}
}
});
}
i am also defining a global value to override the value but i am not able to override the value
function onSave(e) {
var status;
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax(
{
url: '/StudentTransaction/CheckRegistrationNumber',
type: "POST",
data: { 'RegisterNumber': currentValueForSend },
success: function (data) {
status = data.CurrentRegNo;
}
});
if (status.indexOf('true') >= 0)) {
e.preventDefault();
alert("Duplicates not allowed");
return false;
}
}
What i am doing wrong?
This is due to the async nature of these requests.
The sequence as described in your code is:
make the request
check if status is true
get the response
You need to use function callbacks to handle this properly. Try something like this:
function onSave (e){
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax({
url : '/StudentTransaction/CheckRegistrationNumber',
type : "POST",
data : { 'RegisterNumber': currentValueForSend },
success : afterSave
});
}
function afterSave (data){
var status = data.CurrentRegNo;
if (status.indexOf('true') >= 0)) {
e.preventDefault();
alert("Duplicates not allowed");
return false;
}
}
Related
I am trying to save the data by selecting multi checkboxes in datatables. But after ajax call in the submit click the the ajax not hitting success function. It is showing querystring along with the controller/action.Like following
https://localhost:44307/Leaves/Approval?leaveApproveDataTable_length=10&id%5B%5D=11
This is my js
$(document).on('click', '.btn-Approve', function (e) {
var form = this;
var rows = $(table.rows({
selected: true
}).$('input[type="checkbox"]').map(function () {
return $(this).prop("checked") ? $(this).closest('tr').attr('leaveid') : null;
}));
rows_selected = [];
$.each(rows, function (index, rowId) {
console.log(rowId)
// Create a hidden element
rows_selected.push(rowId);
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
var remarks = $('#Remarks').val();
console.log($(this).closest('tr').attr('leaveid'));
$.ajax({
url: '/Leaves/LeaveApproval',
data: { approveId: rows_selected, remarks: remarks },
type: 'POST',
processData: true,
dataType: 'JSON',
success: function (result) {
console.log(result);
debugger;
if (result) {
window.location.href = "/Leaves/Approval";
}
else {
return result;
}
},
error: function () {
}
});
});
This is my controller
public async Task<IActionResult> LeaveApproval(List<int> approveId, string remarks)
{
foreach (int id in approveId)
{
var leave = await _context.Leaves.FindAsync(id);
if (leave == null)
{
return Json(new { success = false });
}
leave.Status = "Approved";
leave.Remarks = remarks;
leave.ApprovedDate = DateTime.Now;
_context.Update(leave);
await _context.SaveChangesAsync();
}
return Json(new { success = true });
}
Kindly help me to solve the issue.
While returning from the controller replace:
return Json(new { success = true }); this line with
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
Basically, I am trying to call controller from views using jQuery ajax but it's not calling controller.
What I have to do is passing my token value from registration page to controller so that I will use its value for user registration.
< script type = "text/javascript" >
document.getElementById('LoginWithAmazon').onclick = function() {
options = {
scope: 'profile'
};
amazon.Login.authorize(options,
function(response) {
if (response.error) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token) {
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: {
token: 'abc'
},
cache: false,
success: function(result) {
alert(result);
}
});
}
function receiveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].Data);
}
}
}
return false;
};
< /script>/
Here below is my controller code
public JsonResult ProfileInfo(string token) {
return Json("test", JsonRequestBehavior.AllowGet);
}
I need to pass the token value from registration page to my controller
Try to change this in the controller
return Json("test", JsonRequestBehavior.AllowGet);
into
enter code herereturn Json(new { value="test" }, JsonRequestBehavior.AllowGet);
and change your js to be like this
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: JSON.stringify({
token: 'abc'
}),
cache: false,
success: function(result) {
alert(result);
}
});
Finally, i have solved the problem.I am unable to call the account controller so i have used my home controller for this purpose.Here below is the code that i have used for calling controller :
<script type="text/javascript">
document.getElementById('LoginWithAmazon').onclick = function() {
options = { scope : 'profile' };
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token)
{
var url = "/home/ProfileInfo?token=" + token;
var request = $.ajax({
url: url,
method: "GET",
dataType: "json"
});
request.done(function (msg) {
var data = [];
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
});
}
}
</script>
I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:
[HttpPost]
public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
{
if (pwd == null || repeatpwd == null)
{
ViewBag.Error = "Insira os campos obrigatórios";
}
else
{
if (pwd == repeatpwd)
{
changePwd_Entidades(Session["ID"].ToString(),pwd);
return Json(true,JsonRequestBehavior.DenyGet);
}
else
{
ViewBag.Error = "As palavras chave precisam de ser iguais";
}
}
return Json(false, JsonRequestBehavior.DenyGet);
}
Script:
<script>
$('.alt-btn').on('click', function () {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home")?pwd=' +
$('#Info_pwd').val() + '&repeatpwd=' + $('#Info_repeatpwd').val(),
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
});
I think you are using incorrect id to get value of password field.
And instead of sending both password to code better approach would be just compare your both password values at client side and if they both are same then parse those values to code side other wise ask user to input same password .
That would be better to Send the data in the data parameter while you're using POST method
var data = JSON.stringify({
'pwd': $('#Info_pwd').val(),
'repeatpwd':$('#Info_repeatpwd').val()
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home"),
data: data,
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
This is for using POST method. If you want to use GET method than it would be fine to pass data in query string.
I want to display a confirmation message when the User delete a record from a grid this what I implement but I have the error message
With the code below the record is deleted but :
the record still in the Grid I have to refresh to see it disapear;
I Have the message Error! even if the record is deleted
3.
#Html.ActionLink("Delete Student", "Delete", new { #StudentID = StudentID }, new { #class="glyphicon glyphicon-pencil", #id=StudentID })
$(document).ready(function () {
$('a.delete').click(OnDeleteClick);
});
function OnDeleteClick(e)
{
var StudentId = e.target.id;
var flag = confirm('You are about to delete this record permanently. Are you sure you want to delete this record?');
if (flag) {
$.ajax({
url: '/Home/DeleteRecord',
type: 'POST',
data: { StudentID: StudentId },
dataType: 'json',
success: function (result) {
alert(result);
$("#" + StudentId).parent().parent().remove();
},
error: function () {
alert('Error!');
}
});
}
return false;
}
Controller :
public ActionResult DeleteRecord(string StudentID)
{
//Code to delete
}
return RedirectToAction("StudentGrid",
"Home");
}
Without seeing which grid you are using try the following:
Get the closest tr tag so you can remove it on success with:
var $tr = $(this).closest("tr");
$tr.remove();
jsFiddle
Set the content message from your controller, the Redirect won't work as it is an ajax call.
public ActionResult DeleteRecord(string StudentID)
{
var success = false;
//Code to delete
// then set success variable
if (success)
{
return Content("Deleted");
}
else
{
return Content("Failed");
}
}
Then from your success handler check the message and remove if needed, the client-side code would end up like this:
function OnDeleteClick(e)
{
e.preventDefault();
var $tr = $(this).closest("tr");
var StudentId = e.target.id;
var flag = confirm('You are about to delete this record permanently. Are you sure you want to delete this record?');
if (flag) {
$.ajax({
url: '/Home/DeleteRecord',
type: 'POST',
data: { StudentID: StudentId },
dataType: 'json',
success: function (result) {
if (result == "Deleted")
$tr.remove();
},
error: function () {
alert('Error!');
}
});
}
return false;
}
public ActionResult DeleteRecord(string StudentID)
{
//Code to delete
}
return Json("Record Is Delete", JsonRequestBehavior.AllowGet);
}
with is response from controller you can show this MSG in alert()
with update grid in project you can use below code is sufficient
$(e).closest("tr").remove();
How can I resume/stop form submission after jQuery ajax call?
I have MVC application, I'm calling an action by json, I want to stop form submission if result came false and to resume if result came true.
Jquery:
$("#formElem").submit(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("Check", "TimeRanges")',
type: "GET",
data: {startRange: $('#SelectedStartTimeRange').val() , endRange: $('#SelectedEndTimeRange').val()},
aync: false,
dataType: 'json',
success: function (data) {
if(data == false) {
$("#rangeexist").html('Error');
return false;
} else {
return true;
}
}
});
});
Action
public JsonResult Check(string startRange, string endRange)
{
var result = false;
if (!String.IsNullOrEmpty(startRange) && !String.IsNullOrEmpty(endRange))
{
TimeSpan spanStart;
TimeSpan.TryParse(startRange, out spanStart);
TimeSpan spanEnd;
TimeSpan.TryParse(endRange, out spanEnd);
var timeRangExisted = _repo.All().Where(x => x.TimeFrom.Equals(spanStart) && x.TimeTo.Equals(spanEnd)).ToList();
if (!timeRangExisted.Any())
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
var ajaxSent = false;
$("#formElem").submit(function (e) {
if ( !ajaxSent )
e.preventDefault();
$.ajax({
url: '#Url.Action("Check", "TimeRanges")',
type: "GET",
data: {startRange: $('#SelectedStartTimeRange').val() , endRange: $('#SelectedEndTimeRange').val()},
aync: false,
dataType: 'json',
success: function (data) {
if(data == false) {
$("#rangeexist").html('Error');
ajaxSent = true;
$("#formElem").submit(); // something like that ....
return false;
} else {
return true;
}
}
});
});