JQuery ajax success never run - c#

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

Related

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

Invalid web service call, missing value for parameter with asmx web service

I have this error : "Invalid web service call, missing value for parameter " when I call a web service method with a parameter.
I'm testing with a web service method without parameter that returns the same type of object and it works well.
Here is my web service method :
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public ResponseStatistic_3 Statistic_3(string klant)
{
Statistic_3[] items = Helper.Helper_Statistic_3(klant).ToArray();
ResponseStatistic_3 response = new ResponseStatistic_3(items);
return response;
}
Here is my javascript code, I retrieve the good value in kla variable :
function getStatistic3() {
var response;
var allstat3 = [];
var kla = $('#Select1').val();
var dataJSon = { klant: kla }
if (kla) {
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: dataJSon,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: false,
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
} else {
alert("statistic 3 null");
}
}
I'm testing too with JSON.stringify({ klant: kla }) and I have the same error.
I looked at several forums but in vain.
What's wrong?
Your webservice method requires a string parameter, but you send the JSON representation of a customer object. I think the build-in JavaScriptSerializer is trying to deserialize your parameter and is causing the error. I adjusted your code in the example below:
function getStatistic3() {
var response;
var allstat3 = [];
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: $('#Select1').val(),
dataType: 'json',
processData: false,
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
}
Webservice method
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public ResponseStatistic_3 Statistic_3(string klant)
{
Statistic_3[] items = Helper.Helper_Statistic_3(klant).ToArray();
ResponseStatistic_3 response = new ResponseStatistic_3(items);
return response;
}
You need to stringify the parameter sefore sending it to the web service using JSON.stringify() method.
function getStatistic3() {
var response;
var allstat3 = [];
var kla = $('#Select1').val();
**var dataJSon = JSON.stringify({ klant: kla })**
if (kla) {
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: dataJSon,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: false,
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
} else {
alert("statistic 3 null");
}
}

how to pass an array of strings from jQuery to controller

How can I pass an array of strings to a controller in asp.net mvc4?
Here is my code
jQuery:
function FnSaveAnalyses(){
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
alert(checked); // it shows all the records without problem
var url = urlBiologieDemande + "Save";
$.post(
url,
data = { values: checked},
traditional= true,
success = function (data) {
DataSaved();
});
}
Controller
public ActionResult save(string[] values)
{
//Traitement
}
When debugging, I get null values.
POST IT AS JSON array.
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
var url = urlBiologieDemande + "Save";
$.ajax({
type: 'Post',
dataType: 'json',
url: url ,
data: JSON.stringify(values:checked),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
}
});
then get the JSON in the Controller
and Parse it ..
see this

jQuery ajax progress

I am trying to create a progree update module when users save some data from my html5 front end. I have the following code but it does not seem to work. I just don't get any percentcompleted values. Any ideas why this might be failing.
The webservices are c# asmx services.
$.ajax({
xhr: function()
{
if (window.ActiveXObject) {
return new window.ActiveXObject("Microsoft.XMLHTTP");
}
else {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
console.log(percentComplete);
alert(percentComplete);
}
}, false);
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
alert(percentComplete);
}
}, false);
return xhr;
}
},
type: "POST",
url: "../service.asmx/SaveSession",
cache: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO),
dataType: "json",
async:false,
success: function (response) {
result = response;
IsDataDirty = false;
},
});
use code below :
{
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(e) {
var percentage = event.loaded / event.total * 100;
//.....
}, false);
}
return xhr;
});
}

Categories