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);
},
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'm trying to pass some data (parameter) from client side (html) to the server side (C# code-behind) to a method, this is done using AJAX in JSON format, but I'm getting the following error:
Unknown Web Method
my AJAX code is:
var jsonObj = { "sCriterion": sCriterion };
$.ajax({
type: "POST",
url: "NewToken.aspx/GetSelection",
data: jsonObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert(data);
alert("We returned: " + result);
}
});
and this is my code-behind method:
[WebMethod]
private static string GetSelection(string selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
var jsonObj = json.Serialize("proceeded");
return jsonObj;
}
The method should be public static to work. Not private !
[WebMethod]
public static string GetSelection(string selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
var jsonObj = json.Serialize("proceeded");
return jsonObj;
}
Your GetSelection method must be public, but you set it private.
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");
}
}
$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "MyService.asmx/GetCompletionList",
data: "{ 'prefixText': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
This is my jQuery code and WebService method. Can any one help me?. GetCompletionList WebService method returns list of string but autocomplete on TextBox shows undefined for all values
public List<string> GetCompletionList(string prefixText)
{
RegistrationBAL _rbal = new RegistrationBAL(SessionContext.SystemUser);
DataSet ds = new DataSet();
_rbal.LoadByContextSearch(ds, prefixText);
List<string> myList = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
myList.Add((string)row[0]);
}
return myList.ToList();
}
Try to change the data in the ajax call as follows
if the auto complete is done for an asp control
data: "{'prefixText':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
or else give as follows
data: "{'prefixText':'" + document.getElementById("requiredID").value + "'}",
edited answer where the auto complete works
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoCompleteService.asmx/GetAutoCompleteData",
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
//alert("Error");
}
});
}
});
}
which resembles your ajax function but in server side I used the web service as below which the get values from the database
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetAutoCompleteData(string PhoneContactName)
{
List<string> result = new List<string>();
string QueryString;
QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["Admin_raghuConnectionString1"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("select DISTINCT PhoneContactName from PhoneContacts where PhoneContactName LIKE +#SearchText+'%'", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", PhoneContactName);
SqlDataReader obj_result = obj_Sqlcommand.ExecuteReader();
while (obj_result.Read())
{
result.Add(obj_result["PhoneContactName"].ToString().TrimEnd());
}
return result;
}
}
}
}
.. Hope this helps :D
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>');
}
}