0

This is what I have in my c# code

using Newtonsoft.Json;
.....
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("id", id.ToString());
d.Add("type", "error");
d.Add("msg", pex.Message);
.....
return JsonConvert.SerializeObject(d);

My AJAX

......
$.ajax({
                    type: "POST",
                    url: "Service1.svc/MyCall",
                    data: JSON.stringify(parameters),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,

                    beforeSend: function () {
                        $("#lblResult").html("loading");
                    },
                    success: function (data) {
                        $("#lblResult").html(data['id']);
                    },
......

This is the response in Firebug

"{\"id\":\"1\",\"type\":\"error\",\"msg\":\"An exception occurred during a Ping request.\"}"

This is the JSON in Firebug

0       "{"
1       """ 
2       "i"
3       "d"
4       """
5       ":"
6       """
7       "1"
8       """
9       ","
10      """
11      "t"
ETC

Problem: I cannot get data['id'] or any data['SOMETHING'].

How can I get it based on the response received? Any other way to do all?

user3912327
  • 1
  • 1
  • 7

1 Answers1

1

This looks like the JSON is not being converted back to a JavaScript object correctly. Try this

success: function (data) { 
if (data.hasOwnProperty("d"))
            {
                var response = JSON.parse(data.d);
                $("#lblResult").html(response["id"]);
            }
            else
            {
                var response = JSON.parse(data);
                $("#lblResult").html(response["id"]);
            }
}

The .d is required as .Net adds this for security reasons, a better explanation than I can give can be found here Why do ASP.NET JSON web services return the result in 'd'?.

Then since the returned value is a JSON string, this needs to be parsed to become the Javascript Object

Community
  • 1
  • 1
NottsCoder
  • 11
  • 3