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.
Related
I'm trying to use AJAX and calling web method like this in my code.
function generate_source(year_source, month_source) {
var gData_source = '';
if (year_source) {
gData_source = [];
gData_source[0] = year_source;
gData_source[1] = month_source;
console.log('first part');
}
else {
var d_source = new Date();
gData_source = [];
gData_source[0] = d_source.getFullYear();
gData_source[1] = d_source.getMonth() + 1;
console.log('second part');
}
var jsonData_source = JSON.stringify({
gData_source: gData_source
});
var ctx = document.getElementById("order_source").getContext('2d');
$.ajax({
url: "dashboard.aspx/getordersource",
data: jsonData_source,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#loader_divsource").show();
},
success: function (response) {
$("#loader_divsource").hide();
var chartLabel = eval(response.d[0]); //Labels
var chartData = eval(response.d[1]); //Data
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: chartLabel,
datasets: [
{
type: 'doughnut',
label: chartLabel,
data: chartData,
backgroundColor: [
"#FF6384",
"#36A2EB",
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
]
}
]
}
});
}
});
}
var d_source = new Date();
gData_source = [];
$('#year_source').val(d.getFullYear());
$('#month_source').val(d.getMonth() + 1);
generate_source('', '');
My web method is like this;
[System.Web.Services.WebMethod]
public static List<string> getordersource(List<int> gData)
{
DataSet ds = ws_db.get_Dataset_order_source();
var returnData = new List<string>();
......
return returnData;
}
Whenever I try to run this data, my breakpoint for the web method is not hit. Further, if i use the same method without data, i don't get this error. It's driving me crazy.
I think your problem is in this code :
var jsonData_source = JSON.stringify({
gData_source: gData_source
});
you are trying to serialize array with key value pair that it is become invalid.
change to this :
var jsonData_source = JSON.stringify(gData_source);
also your web method should be like this :
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.JSON)]
// just return a string, not list, your JSON string should have contain all your enumerable in your string Data
public static string getordersource(List<int> gData)
{
DataSet ds = ws_db.get_Dataset_order_source();
JsonSerializer serializer = new JsonSerializer();
var returnData = serializer.serialize(ds);
......
return returnData;
}
Hope it helps.
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) { }
});
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 problem in my AjaxHandler.ashx becouse the context.Request["Action"] is null when I send it using JQuery call can someone help me
Note: I'm using html controller not asp,net server controller
<script type="text/javascript">
$(function () {
$("#btnSearch").click(function () {
/*var skill = $("#ddlSkills option:selected").val();
var types = $("#ddlTypes option:selected").val();
var topics = $("#ddlTopics option:selected").val();
var sortBy = $("#ddlSortBy option:selected").val();
*/
$.ajax({
url: "../ideapark/DesktopModules/ResourcesFilter/AjaxHandler.ashx",
contentType: "application/json; charset=uft-8",
type: "POST",
data: $('form').serialize(),
success: function(data) {
for(var i = 0; i < data.length; i++)
{
//t ajax handler recollection of resources.
//U NEED TDESERIALIZE
var resID = data.response[i].ID;
var summary = data.response[i].Summary;
var pageID = data.response[i].PageID;
var name = data.response[i].Name;
var createdOn = data.response[i].CreatedOn
var Total = data.response[i].Total;
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(errorThrown);
alert(XMLHttpRequest);
alert(textStatus);
console.log(errorThrown);
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
});
});
</script>
/// <summary>
/// Summary description for AjaxHandler
/// </summary>
public class AjaxHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
//context.Response.Write("Hello World");
string response = "";
string var = context.Request["Action"].ToString();
switch (context.Request["Action"])
{
case "ResponseFilterSearch":
response += "{";
Dictionary<string, Object> jsonObject = new Dictionary<string, object>();
string skill = context.Request["Skill"].ToString();
string type = context.Request["Type"].ToString();
string focus = context.Request["focus"].ToString();
string keyword = context.Request["Keyword"];
string sortby = context.Request["SortBy"];
string pageNumber = context.Request["pagenumber"];
SqlDataProvider sqlConn = new SqlDataProvider();
DataSet dsResults = SqlHelper.ExecuteDataset(sqlConn.ConnectionString, "spResourceSearch", skill, type, focus, keyword, sortby, pageNumber);
foreach (System.Data.DataRow row in dsResults.Tables[0].Rows)
{
response += "\"ID\":" + "\"" + row["Id"].ToString() + "\"";
response += "\"Summary\":" + "\"" + row["summary"].ToString() + "\"";
response += "\"PageID\":" + "\"" + row["pageId"].ToString() + "\"";
response += "\"Name\":" + "\"" + row["name"].ToString() + "\"";
response += "\"CreatedOn\":" + "\"" + row["createdOn"].ToString() + "\"";
response += "\"Total\":" + "\"" + row["total"].ToString() + "\"";
}
response += "}";
break;
}
//this returns a json string
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
You seem to be mixing up contentType and dataType.
contentType represents the the content type of the request body(that is the data you're sending to the server), which you've set to json which is not what $('form').serialize() will produce. $('form').serialize() produces data in application/x-www-form-urlencoded which is the default in $.ajax.
Now dataType is the content type of the response body(which is the data you receive from the server) which from your code should be json.
$.ajax({
url: "../ideapark/DesktopModules/ResourcesFilter/AjaxHandler.ashx",
dataType: "json",
type: "POST",
data: $('form').serialize(),
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
....
}
});
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)},