function not returning message from ajax call - c#

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

Related

JQuery ajax success never run

i have this jquery code, sending items to controller and download from controller, everything is fine
downloads is fine, i check response from in Chrome Network Tab is okay. but success function never run after process done. (i'm using async:false; already)
$(document).on('click', '#baslat', function (e) {
var token = $("#token").val();
var islemler = [];
var secililer = [];
$.each($("input[class='cc']:checked"), function () {
var islem = {};
islem.IslemTuru = $(this).attr("id");
islemler.push(islem);
});
$.each($("tr[class='sec']"), function () {
if ($(this).children('td:eq(1)').children("input[type='checkbox']").prop('checked')) {
var beyan = {};
beyan.Id = $(this).attr("id");
beyan.TahakkukId = $(this).data("id");
beyan.KisaKod = $(this).children('td:eq(2)').html();
beyan.BeyannameTuru = $(this).children('td:eq(4)').html();
beyan.Ay = $(this).children('td:eq(5)').html().substring(8, 10);
beyan.Yil = $(this).children('td:eq(5)').html().substring(11, 16);
secililer.push(beyan);
}
});
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string",
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});
});
The controller is here. I have to use Thread.Sleep (1000) in the method. because the server on which I want to download files wants 1 second to pass between each request.
public async Task<string> BeyanAl(List<Beyanname> secililer, List<Islem> islemler, string token)
{
bool indir = true;
bool yazdir = false;
bool gonder = false;
foreach (var islem in islemler)
{
if (islem.IslemTuru =="cbyazdir")
{
yazdir = true;
}
if (islem.IslemTuru == "cbgonder")
{
gonder= true;
}
}
foreach (var GelenBeyan in secililer)
{
string YolAdi = YolHazirla(GelenBeyan);
string DosyaAdi = DosyaAdiHazirla(GelenBeyan);
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Beyan", GelenBeyan.Id, "");
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Tahakkuk", GelenBeyan.Id, GelenBeyan.TahakkukId);
}
return "İndirildi";
}
here is chrome response screens
r1
r2
There is no 'string' data type in ajax datatypes make it json or text
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string", <-- make it json or text
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});

ajax posting formdata error status 200 OK

I am trying to upload file using Ajax.
The Error status is 200 ok .
Response text is my MasterPage HTML Code.
The Request never went to the Back-end as i am debugging with a breakpoint into the method.
so far i have tried this.
C# WebMethod
[HttpPost]
public void Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
file.SaveAs(path);
}
}`
Ajax Request
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
in ajax call you have to delete dataType: json because files must be sent multipart/form-data
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
Please try this code
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
return reader.result;
};
reader.onerror = function (error) {
return '';
};
}
function uploadFiles() {
var files=[];
$.each(files, function (key, value) {
var x=getBase64(value)
if(!!x)
files.push(x);
});
$.ajax({
type: 'POST',
url: '/Home.aspx/Upload',
data: JSON.stringity({files:files}),
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
[System.Web.Services.WebMethod]
public static void Upload(string[] files)
{
//Convert base64 to file format and save
}

How to I pass parameters from ajax to web method?

I am doing a update operation from my web method. What I am doing is I have two text boxes inside my webForm1.aspx page. I am trying to post my these textboxes values to web method so my update operation will run. Below is my code:
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: '{val1:"' + uval1 + '",val2:"' + uval2 + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}
My update procedure is running fine but when I put debugging point on my web method and check parameters values it contain undefined values and don't getting correct values from text boxes. below is my codebehind code. Please help me here.
[WebMethod]
public static bool updateData(string val1,string val2)
{
var db = new dbDataContext();
var query = (from e in db.Employees
where e.ID == up_id
select e).FirstOrDefault();
query.EMP_FNAME = val1;
query.EMP_MNAME = val2;
db.SubmitChanges();
return true;
}
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: {val1: uval1 ,val2: uval2 },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}
and you must have to ensure that passed parameters must match webmethod params in server side.
[WebMethod]
public static bool updateData(string val1,string val2)
{
using (var db = new dbDataContext())
{
var query = (from e in db.Employees
where e.ID == up_id
select e).FirstOrDefault();
query.EMP_FNAME = val1;
query.EMP_MNAME = val2;
db.SubmitChanges();
}
return true;
}
You need to send an array from the data parameter in ajax. Try something like:
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: {val1: uval1 ,val2: uval2 },
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}

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.

Resume form submission after $.ajax call

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

Categories