btalbot
btalbot

Reputation: 167

Why can't I use my JSON data?

I am trying to read some JSON data from an AJAX function. Here is the AJAX I am using:

             $.ajax({
                type: 'POST',
                cache: false,
                url: 'Default.aspx/GetCoords',
                data: "{}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data) {
                    var text = JSON.stringify(data);
                    $("#jsonData").html(text);
                    alert(text);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });

I also have use JSON.parse in place of stringify, and objects return undefined or not at all. This comes from a C# function which looks like this:

    [WebMethod]
    [ScriptMethod]
    public static string GetCoords()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                Dictionary<string, object> row;
                foreach (DataRow dr in dt.Rows)
                {
                    row = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, dr[col]);
                    }
                    rows.Add(row);
                }
                System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
                return serializer.Serialize(rows);                
            }
        }
    }

It is returning JSON data: Here is what it looks like on the Debugger Console and when I call the function in a paragraph tag:

[{"DrawID":925,"xCoord":466,"yCoord":201},{"DrawID":924,"xCoord":385,"yCoord":318},{"DrawID":923,"xCoord":768,"yCoord":159},{"DrawID":922,"xCoord":543,"yCoord":214},{"DrawID":921,"xCoord":329,"yCoord":172}]

However, when I send it to the paragraph tag in JQuery or call it in an HTML paragraph, here is what it looks like:

{"d":"[{\"DrawID\":925,\"xCoord\":466,\"yCoord\":201},{\"DrawID\":924,\"xCoord\":385,\"yCoord\":318},{\"DrawID\":923,\"xCoord\":768,\"yCoord\":159},{\"DrawID\":922,\"xCoord\":543,\"yCoord\":214},{\"DrawID\":921,\"xCoord\":329,\"yCoord\":172}]"}

I have two questions: (1) Why am I not able to use this data to insert the xCoords and yCoords into a canvas? I have tried many formats: (data.d[0].xCoord, d[0].xCoord, text.d[0].xCoord, text[0].xCoord, and so on). (2) Is the second format above going to be a problem in trying to extract that data for painting on the canvas (it's the backslashes that I am wondering about)?

Thanks.

Upvotes: 0

Views: 148

Answers (4)

lujcon
lujcon

Reputation: 586

[WebMethod]
[ScriptMethod]
public static Dictionary<string, object>[] GetCoords()
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
            return rows.ToArray();                
        }
    }
}

Java script:

         $.ajax({
            type: 'POST',
            cache: false,
            url: 'Default.aspx/GetCoords',
            data: "{}",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {

                $.each(data, function(index, value) {
                    var x = value.xCoord;
                    /// do something with it ;)
                });
                var text = JSON.stringify(data);
                $("#jsonData").html(text);
                alert(text);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });

Upvotes: 0

btalbot
btalbot

Reputation: 167

I had to return rows in my C# code as @lujcon said:

[WebMethod]
[ScriptMethod]
public static List<Dictionary<string, object>> GetCoords()
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
            return rows;                
        }
    }
}

Then I had to change my var text = JSON.stringify(data); to var text = JSON.stringify(data.d); as @JustinRusso said. Works now. Thanks, everyone.

Upvotes: 0

Justin Russo
Justin Russo

Reputation: 2214

In your success function, you do not stringify or json.Parse the 'data' variable, but rather the data.d variable. 'd' is the member of the json return that you need to parse.

So, change, var text = JSON.stringify(data); to var text = JSON.stringify(data.d); and you should be golden.

Upvotes: 2

jpriebe
jpriebe

Reputation: 824

You need to use parseJSON, as such:

myThing = {"d":"[{\"DrawID\":925,\"xCoord\":466,\"yCoord\":201},{\"DrawID\":924,\"xCoord\":385,\"yCoord\":318},{\"DrawID\":923,\"xCoord\":768,\"yCoord\":159},{\"DrawID\":922,\"xCoord\":543,\"yCoord\":214},{\"DrawID\":921,\"xCoord\":329,\"yCoord\":172}]"};

myJSON = $.parseJSON(myThing.d);
alert (myJSON[0].DrawID); //etc

Upvotes: 1

Related Questions