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)},
Related
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 a WebMethod which gets data that I want to fill DropDown with in a DataSet.
Currently I am filling the dropdown using a hardcoded object. But I want to replace this hard coded object with data returned by webmethod.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return ds.GetXml();
}
CLIENT SIDE(UPDATE 1):
<script type = "text/javascript">
function GetDropDownData() {
var myDropDownList = $('.myDropDownLisTId');
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(jQuery.parseJSON(data.d), function () {
myDropDownList.append($("<option></option>").val(this['FieldDescription']).html(this['FieldCode']));
});
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
console.log(response.d);
alert(response.d);
}
</script>
function GetDropDownData() {
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data.d)
{
$.each(data.d, function (){
$(".myDropDownLisTId").append($("<option />").val(this.KeyName).text(this.ValueName));
});
},
failure: function () {
alert("Failed!");
}
});
}
var theDropDown = document.getElementById("myDropDownLisTId");
theDropDown.length = 0;
$.each(items, function (key, value) {
$("#myDropDownLisTId").append($("<option></option>").val(value.PKId).html(value.SubDesc));
here "SubDesc",PKId describes the value getting out of Database., u need to separate your value from dataset.
From the WebMethod, don't send DataSet directly, send XML...
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
DataSet ds = new DataSet();
ds.Tables.Add("Table0");
ds.Tables[0].Columns.Add("OptionValue");
ds.Tables[0].Columns.Add("OptionText");
ds.Tables[0].Rows.Add("0", "test 0");
ds.Tables[0].Rows.Add("1", "test 1");
ds.Tables[0].Rows.Add("2", "test 2");
ds.Tables[0].Rows.Add("3", "test 3");
ds.Tables[0].Rows.Add("4", "test 4");
return ds.GetXml();
}
Before Ajax call...
var myDropDownList = $('.myDropDownLisTId');
Try like below...(inside Ajax call)
success: function (response) {
debugger;
$(response.d).find('Table0').each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
myDropDownList.append(option);
});
},
Note:
OptionValue and OptionText are the Columns of DataSet Table.
$(response.d).find('Table0').each(function (){}) - Here Table0
is the name of Table inside DataSet.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return DataSetToJSON(ds);
}
public static string DataSetToJSON(DataSet ds)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable dt in ds.Tables)
{
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
dict.Add(dt.TableName, arr);
}
var lstJson = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
return lstJson;
}
Ajax Call
function GetAssociation() {
var myDropDownList = $("#myDropDownLisTId");
var post_data = JSON.stringify({ "name": "xyz"});
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: post_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
json_data = JSON.parse(response.d);
myDropDownList.empty();
for(i=0; i<json_data.Table.length; i++)
{
myDropDownList.append($("<option></option>").val(json_data.Table[i][0]).html(json_data.Table[i][1]));
}
},
failure: function (response) {
alert(response.d);
}
});
}
// We can bind dropdown list using this Jquery function in JS script
function listDropdownBind() {
var requestId = 123;
$.ajax({
type: "POST",
url: "/api/ControllerName/ActionName?param=" + param, // call API with parameter
headers: { 'rId': requestId },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var optionhtml1 = '';
var optionhtml1 = '<option value="' +
0 + '">' + "--Select--" + '</option>';
$("#ddlName").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data.d[i].Value + '">' + data.d[i].Text + '</option>';
$("#ddlName").append(optionhtml);
});
}
});
};
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 am making a call to a webservice from jquery and trying to return an List (I have also tried a string[]). When I get the results back I can see it holds an array with the values I need, but I can not iterate through them in Javascript because there is no length value.
my C# Webservice is as follows:
[WebMethod]
public string[] GetMultiChoiceOptions(int keyId)
{
string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["OBConnectionString"].ConnectionString;
SitesUtil db = new SitesUtil(connectionString);
List<MultiChoiceOption> keys = db.GetMultiChoiceOptions(keyId, 1); //TO DO CHANGE THIS TO REAL USERID
return keys.Select(a => a.OptionValue).ToArray();
}
and My Jquery/javscript call is as follows:
function GetKeys(keyid) {
var pageUrl = '<%=ResolveUrl("~/WebService/UpdateDatabase.asmx")%>'
$.ajax({
type: "POST",
url: pageUrl + "/GetMultiChoiceOptions",
data: '{keyId:' + keyid + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: GetKeysSuccessCall,
error: OnErrorCall
});
}
function GetKeysSuccessCall(response) {
/* TO DO */
var i = 0;
for (i =0; i < response.length; i++) {
$("#popupList").append('<li>' + response[i] + '</li>');
}
}
I'm not sure how I deal with an array without a length in javascript?
I think you should use first of all the JSONSerializer to send the rigth json structure to the client.
You should return only a string, which has the JSON format, and then it will work!
First, use Google Console. Best and helpful.
To see what you receive, use console.log(response); (instead of alert and do NOT use in IE because it doesn't know console)
try first of all
$.ajax({
type: "POST",
url: pageUrl + "/GetMultiChoiceOptions",
data: '{keyId:' + keyid + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
GetKeysSuccessCall(response);
},
error: function(msg) {
OnErrorCall(msg);
}
});
And one more :
function GetKeysSuccessCall(response) {
/* TO DO */
var i = 0;
for (i =0; i < response.length; i++) {
$("#popupList").append('<li>' + response[i] + '</li>');
}
}
repsonse must be instead of item
I cant explain why it works, but what I needed to do was get the response.d value....
So this was the solution in the end:
function GetKeysSuccessCall(response) {
/* TO DO */
var result = response.d;
var i;
for (i = 0; i < result.length; i++)
{
$("#popupList").append('<li>' + result[i] + '</li>');
}
}
(if someone can explain where the .d comes from?)
You can use the .each function like so
success: function (response) {
var options= response.d;
$.each(options, function (index, option) {
$("#popupList").append('<li>' + response[option] + '</li>');
});
},
or
function GetKeysSuccessCall(response) {
/* TO DO */
var i = 0;
for (i =0; i < response.d.length; i++) {
$("#popupList").append('<li>' + response.d[i] + '</li>');
}
}
I've a dynamically created HTML table in the Server side code(using C#). When i pass that to client site using JASON. I couldn't able to receive that code in the client site. this is my code in the Server Side.
$.ajax({
type: "POST",
url: "ExcelUpload.asmx/UploadFile",
data: JSON.stringify({ XML: XMLDoc}),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#Status").html("<br><center><img src='ajax-loader.gif'/></center>");
},
success: function (result) {
var output = "";
var re = eval('(' + result.d + ')');
if (re.length > 0) {
for (var i in re) {
var xl = re[i];
switch (parseInt(xl.status)) {
case 1: { output = xl.message; break; }
case 2: { output = xl.message; break; }
}
}
$("#Status").html(output);
}
},
error: function (result) {
$("#Status").addClass("error");
$("#Status").html(result.d);
}
});
In that server side code I'm generating the HTML table using this code
HTML += "<table id='excelDoc'>";
HTML += "<tr><th>Date</th><th>Description</th><th>Reference</th><th>Nominal Code</th><th>Dept Code</th><th>Debit</th><th>Credit</th></tr>";
HTML += "<tr><td>" + eDoc.posting_Date.ToShortDateString() + "</td><td>" + eDoc.Description + "</td><td>" + eDoc.Ref_Number + "</td><td></td><td></td><td class='db'></td><td class='cr'></td></tr>";
HTML += "";
status = "{status : 1 , message : " + HTML + "}";
return " ["+ status+ "]";
Please Help me.
why are you doing result.d ?
Should it not be simply result ?
1 thing I notice more, in your AJAX request, your
dataType: "json"
but you are returning a simple string. Change to
dataType:"text"
and then try returning the string. It would def work