Resume form submission after $.ajax call - c#

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

Related

Why querystring after ajax call while using datatable checkboxes?

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

jQuery AJAX Not Calling A C# Function In ASP.NET MVC

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>

Sending object to a controller in asp.net mvc using ajax

I have issue with sending object contains array to a controller
this is my js code
var messageId = 0;
function DraftMessage()
{
var to = [];
var i = 0;
$('#to option:selected').each(function (index, element) {
to[i++] = $(element).val();
});
console.log(to);
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage", "Activities")",
datatype: "json",
traditional: true,
async: false,
data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
beforeSend: function () { }
}).done(function (Id) {
console.log(Id);
messageId = Id;
});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
and this is my controller side
public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
{
return new MessageActions().DraftMessage(draftMessage);
}
my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.
Can you change your request and use
dataType: "json",
contentType: "application/json;charset=utf-8",
This should work. Please let me know.
Try this. Push your object to array and send it as Json.
array.push({yourobject datas here})
$.ajax({
type: "POST",
url: '/DraftMessage/Activities',
contentType: 'application/json',
data: JSON.stringify(array),
success: function (d) {
..
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Convert your controller function's return type to JSonResult.
Hope helps.
do you want upload file using ajax ?!!
use the normal usage of form not the Ajax.BeginForm then in form submit event
write your code like this:
$('#Form').submit(function () {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = $('#Image').val();
if (file) {
var fname = $('#Image')[0].files[0].name;
if (CheckFile(file)) {
var uploadFile = document.getElementById('Image').files[0];
var myArray = [];
myArray.push(uploadFile);
if (myArray.length > 0) {
for (var i = 0; i < myArray.length; i = i + 1) {
fd.append("File1", myArray[i]);
}
}
}
else {
return false;
}
}
fd.append("ID", messageId);
fd.append("Title", $('#Title').val());
fd.append("Project", $('#Project').val());
fd.append("AreaId", $('#AreaId').val());
fd.append("Body", $('#messageBody').val());
var form = $('#Form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
fd.append("__RequestVerificationToken", token);
xhr.open("POST", "/ControllerName/Action/", true);
xhr.send(fd);
xhr.addEventListener("load", function (event) {
if (event.target.response != "OK") {
OnFail(event.target.response);
}
else {
OnSuccess(event);
}
}, false);
return false;
})
server side in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionName(Model pModel){
HttpPostedFileBase File = Request.Files["File1"];
if (File != null && File.ContentLength != 0){
//do what you want
return Content("OK");
}
else{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Error Messages", System.Net.Mime.MediaTypeNames.Text.Plain);
}
}
You can try a different approach. You can serialize your entire form by doing something like this:
var formdata = $("#frmEmailInfo").serialize();
and then post it to the Controller:
$.ajax(
{
type: "POST",
data: formdata,
dataType: 'json',...

function not returning message from ajax call

I want my function, which does an ajax call to controller, to return message from response.
I've tried this, but it doesnt work. How can acchieve my goal? is there a better solution for this?
var exists = personExists ();
if (exists != null) {
alert('The person already exists');
return;
}
var personExists = function () {
var exists = false;
var errorMsg = null;
$.ajax({
url: "#Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
errorMsg = response.message;
}
}
});
if (exists)
return errorMsg;
return null;
};
You can do that with callback functions;
var personExists = function (callback) {
var exists = false;
var errorMsg = null;
$.ajax({
url: "#Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
errorMsg = response.message;
callback(exists, errorMsg);
}
}
});
if (exists)
return errorMsg;
return null;
};
And usage;
personExists(function(exists, err) {
if (exists != null) {
alert('The person already exists');
return;
}
});
Simply, you can pass exists and errorMsg to callback. See here for further detail on callback functions
You need to use a callback:
function getErrorMessage(message) {
//do whatever
}
Inside the AJAX request:
$.ajax({
url: "#Url.Action("PersonExist", "Person")",
type: "POST",
dataType: 'json',
data: { name: self.name(), socialSecurityNumber: self.socialSecurityNumber() },
async: false,
contentType: "application/json",
success: function (response) {
if (response.exists) {
exists = true;
getErrorMessage(response.message); //callback
}
}
});

MVC post with data and return json data

I have a controle like this
public JsonResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
I need to get that by following json by ajax request
var sizes = [];
$.ajax({
type: 'POST',
async: false,
data: { 'Id': selectedId },
url: "/<Controler name>/GetSizes",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
return false;
},
success: function (result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}
});
But this give me an Server error. How can i fix this.
replace your
url: "/<Controler name>/GetSizes",
by
url: "#Url.Action("GetSizes", "Controller_Name"),
and is you Ajax will have to be
async: false?
then try to use this as your Action
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
Also, try to put a break point on your action and see in debug mode if your Ajax reaches your Action.
this my demo, you can do the same:
$.ajax({
url: '#Url.Action("CheckCity", "BookingStarts")',
data: { packageId: packageid, cityId: valuecities[valuecities.length - 1] },
type: 'POST',
dataType: 'json',
success:
function(result) {
if (result.Status == true) {
$('#CheckoutDateHotel_#item.CityId').val(result.Date);
}
}
});
in controller :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CheckCity(int packageId, int cityId)
{
var packageCityModel = PackageDetails.GetPackageCitiesByPackageId(packageId).OfType<HMSService.PackageCity>();
var package = new PackageReservationMasterDal();
var itemPackage = package.GetPackageDetailByPackageId(packageId);
var result = "";
var city = packageCityModel.FirstOrDefault(x => x.CityId == cityId);
if (city != null)
{
result = itemPackage.TravelDateFrom.AddDays(city.NoOfNights).ToShortDateString();
}
return Json(new { Status = true, Date = result });
}
See the problem here is that you have not stringified your Data Transfer Object(DTO).
A cleaner approach will be this.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.0/json3.js"></script>
<script type="text/javascript">
var sizes = [];
var DTO = { 'Id': selectedId };
$.ajax({
type: 'POST',
async: false,
data: JSON.stringify(DTO),
url: "#Url.Action("GetSizes", "Home")",
dataType: 'json',
contentType: 'application/json'
}).done(function(result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}).fail(function(xhr) {
alert('Error: ' + xhr.statusText);
return false;
});
</script>
Please note the use of
JSON.stringify
#Url.Action helper
jqXHR.done(function( data, textStatus, jqXHR ) {});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
Also you are using async=false which I guess is to grab all the sizes before exiting from the function. jQuery.deferred will be an interesting read.

Categories