the code:
[WebMethod]
public static string [] GetMorechatMsgs(int toclient, int fromclient, int top)
{
string [] List =new string[2];
int chatcount = new ChatPage().GetAllMsgCount(toclient, fromclient);
if (top <= chatcount)
{
string toreturn=new ChatPage().GetChat(fromclient, toclient, "", top);
List[0]= toreturn;
List[1] = chatcount.ToString();
}
else {
List = null;
}
return List;
}
html:
$.ajax({
type: "POST",
url: "ChatPage.aspx/GetMorechatMsgs",
data: "{'toclient':'" + ToClient + "','fromclient': '" + fromClient + "','top': '" + $("#MsgCount").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != "") {
// how to read the returned table
}
else {
}
},
error: function (xhr) {
alert("responseText: " + xhr.responseText);
}
});
How can i read the returned string array on success ?
serialize the list of your string i.e
change your method to this:
[WebMethod]
public static string GetMorechatMsgs(int toclient, int fromclient, int top)
{
/// your usual code
return new JavaScriptSerializer().Serialze(list);
}
and read returned data like this:
success: function (data) {
var jsonData =$.parseJSON(data.d);
for(var i=0; i<jsonData.length; i++){
console.log(jsonData[i]);
}
}
The WebMethod will return your string array in the form ["string", "string", "string", ...], therefore, simply loop through the array in the way Manish demonstrated:
success: function (data) {
var jsonData =$.parseJSON(data.d);
for(var i=0; i<jsonData.length; i++){
var theString = jsonData[i];
//Do something with the string
}
}
Related
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);
});
}
});
};
I have the following ajax call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/LoadCount.aspx/GetCounts",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
alert(myObj.length);
for (var i = 0; i < myObj.length; i++) {
alert(myObj[0]);
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I am getting undefined when I alert the length
Here's my Method in my LoadCount.aspx
[WebMethod]
public static string ObtenerContador()
{
List<MenuItem> menu =(List<MenuItem>)HttpContext.Current.Session["MenuItems"];
Dictionary<string, int> dic = new Dictionary<string, int>();
foreach (MenuItemAMostrar item in menu)
{
dic.Add(item.ControlID,1);
};
return new JavaScriptSerializer().Serialize(dic); //or any other suggested serialization method
}
this is what I am getting in the success function:
{"MenuCLESAAsignar":1,"MenuOCGestores":1,"MenuOcAAutorizar":1,"MenuOcAAutorizarBanco":1,"MenuOCGestoresObservadas":1,"MenuCLESActivos":1,"MenuParametros":1,"MenuCLESConAddendaAAprobarSup":1,"MenuPendienteAprobacion":1,"MenuConsultaCLES":1}
The question is, how do I deserialize that dictionary in my ajax success function?
Once deserialized, how do I populate it, obtaining the data?
thanks!
As somebody else mentioned, you just use JSON.parse() to parse the data.
From there it just creates an object, and you can access the data with ..
Like so:
http://jsfiddle.net/SJGLF/1/
var myData = JSON.parse(jsonData);
for(var i in myData)
{
console.log(i + " = " + myData[i]);
}
Are you looking for this?
success: function (data)
{
var myObj = JSON.parse(data.d);
},
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)},
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>');
}
}