Guys I have problem with my ajax post request and it is not working for some dates i.e it does not hits controller but for some dates it works fine please help me to find out the bug
Here is my code
$("#getInfo").click(function ()
{
var elementValue = document.getElementById("tournamentID").value;
var startDateValue = document.getElementById("filterDateStartnew").value;
if (elementValue == null || elementValue == "" || startDateValue == null || startDateValue == "")
{
alert("please enter TournamentID and timestamp to get Info");
return false;
}
$.ajax({
type: "POST",
cache: false,
url: '/reports/gettournamentinfo',
data: { tournamentID: elementValue,date: startDateValue },
success: function (data)
{
var select = document.getElementById("TournamentLevel");
var length = select.options.length;
//Delete All Options
$('#TournamentLevel')
.find('option')
.remove()
.end()
var opt = document.createElement("option");
opt.text = "Any";
opt.value = -1;
document.getElementById("TournamentLevel").options.add(opt);
var count = data[0];
for (var i = 1; i <= count; i++)
{
var opt = document.createElement("option");
opt.text = i;
opt.value = i;
document.getElementById("TournamentLevel").options.add(opt);
}
for (var index = 1; index < data.length; ++index)
{
var opt = document.createElement("option");
opt.text = data[index];
opt.value = data[index];
document.getElementById("RunID").options.add(opt);
}
$("#SubmitForm").removeAttr('disabled');
},
error: function(data)
{
alert("there was no info for that tournamentID and that date");
$.unblockUI();
$('#TournamentLevel')
.find('option')
.remove()
.end()
return false;
}
});
return false;
});
Check for the data formats. For example if the client using dd/mm/yyyy and the server is expecting mm/dd/yyyy, you will see a HTTP 500 error as the model binder will fail to do the binding
Change your ajax post method like below.
$.ajax({ url: "/reports/gettournamentinfo", contentType: "application/json; charset=utf-8", type: "POST",
data: '{"tournamentID":"' + elementValue+ '", "date":"' + startDateValue + '"}',
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});
Related
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.");
}
});
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',...
i write two functions in jquery client side and c# asp.net server side , i try post json list object to web method but i see error..
jquery code :
function UpdateCart(tableid) {
var page = "Account/Cart.aspx";
var method = "Update_Cart";
var url = "http://" + host + "/" + page + "/" + method;
$(".popup").show();
var cartlist = new Array();
for (var i = 68; i < 71; i++) {
var cart = new Object();
cart.ID = i;
cart.Quantity = 6;
cartlist.push(cart);
}
var jsonArray = JSON.parse(JSON.stringify(cartlist))
$.ajax({
type: "POST",
url: url,
data: jsonArray,
contentType: "application/json; charset=utf-8",
datatype: "json",
async: "true",
success: function (response) {
// success message or do
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject == 1) {
window.location.href = "http://" + host + "/Account/cart";
} else {
$(".errMsg").text("نام کاربری یا رمز اشتباه است");
$(".errMsg").removeClass("alert");
$(".errMsg").addClass("alert alert-danger");
}
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
c# web method :
[WebMethod]
public static string Update_Cart(string[] Carts)
{
if (Carts != null)
{
foreach (var item in Carts)
{
com_Shop_Carts cart = new com_Shop_Carts()
{
Quantity = item.Quantity,
AddDate = DateTime.Now
};
com.shop.ProductManager.Update_Cart(item.ID, cart).ToString();
}
}
return "1";
}
after run i see error 500 and i can't resolve it please give me solution for resolve it.
Apart from this : var jsonArray = JSON.parse(JSON.stringify(cartlist))
Try this : var json={"Carts":cartlist}; then, var jsonArray=JSON.stringify(json);
and remove datatype:json from the ajax call.
Hope this helps.
I have two ASP ListBoxes. As you can see below, lbAvailable is populated on PageLoad with WebMethod and populates all cities. LbChoosen is populated depending on DropDown Value Chosen. The Dropdown has 4 options(ALL, Top25, Top50, Top100). for example if you choose Top 25 which is value 4, lbChosen populates top 25 cities (This all works).
MY PROBLEM IS lbAvaliable always populates all cities. So if i chose top 25 which populates top25 cities into lbChoosen, how can those value (top25 cities) be removed from lbAvailable
function LoadMarketsAvailableJS() {
var ddlFootprint = $('#ddlFootprint');
var lbChoosen = $('#lbChoosen');
var lbAvailable = $('#lbAvailable');
lbChoosen.empty();
var SelectedMarkets = [];
var url = "";
//Load lbAvailable on Page Load with all Markets
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Campaign.aspx/LoadAvailableMarkets",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
$("#lbAvailable").append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function(result) {
alert("Error");
}
});
//Check DropdownList
if (parseInt(ddlFootprint.val()) == 1) {
url = 'Campaign.aspx/LoadAvailableMarkets';
} else if (parseInt(ddlFootprint.val()) == 2) {
url = 'Campaign.aspx/LoadTop100Markets';
}
else if (parseInt(ddlFootprint.val()) == 3) {
url = 'Campaign.aspx/LoadTop50Markets';
}
else if (parseInt(ddlFootprint.val()) == 4) {
url = 'Campaign.aspx/LoadTop25Markets';
}
else if (parseInt(ddlFootprint.val()) == 5) {
url = 'Campaign.aspx/LoadAvailableMarkets';
}
//Load Select Dropdown Value to lbChoosen
if (url.length > 0) {
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
}
}
Assuming I've understood what you're asking, if you want to remove options from lbAvailable as they're added to lbChoosen you should be add the following line:
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
So your code will look something like:
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
}
}
},
i have this ajax call
function findPICKey() {
filter = document.getElementById('MainCT_dtvJobVac_PIC').value;
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: "{listuser:" + JSON.stringify(resultarr) + ", keyword:'" + JSON.strigify(filter)+ "'}",
dataType: 'json',
url: 'SvcAutoComplete.asmx/GetPICKey',
success: function (result) {
result = JSON.parse(result.d);
document.getElementById('<%= dtvJobVac.FindControl("PICKey").ClientID %>').value = result;
},
error: function (result) {
alert("error getting pic key");
}
})
}
web method
[WebMethod]
public string GetPICKey(List<BO> listuser, string keyword)
{
//List<BO> ListObj = new List<BO>();
//ListObj = (List<BO>)Session["ListPIC"];
//ListObj = listuser;
//string key = string.Empty;
//for (int i = 0; i < ListObj.Count; i++)
//{
// if(ListObj[i].label == keyword)
// {
// key = ListObj[i].value;
// break;
// }
//}
//return key;
return "";
}
for some reason my web method not called, i put a break point, but it does not triggered, what i do wrong here? btw resultarr is an object.
Just checking, but you know your second stringify is spelt wrong?
"JSON.strigify" :)
if you call webservice from localhost, you should check url
eq:
http://localhost/HenryChunag/SvcAutoComplete.asmx
url should be :
url: '/HenryChunag/SvcAutoComplete.asmx/GetPICKey'
I think problem is in
data: "{listuser:" + JSON.stringify(resultarr) + ", keyword:'" + JSON.strigify(filter)+ "'}",
it should be
data: {listuser:"+ JSON.stringify(resultarr) +" , keyword:" + JSON.strigify(filter)+ "},
or
data: {listuser:JSON.stringify(resultarr) , keyword:JSON.strigify(filter)},