How to pass data from [webmethod] to javascript object using Ajax/json call

Hi, I'm going through the steps to create a webmethod datatable, convert the datatable to a json string and then post the data to a webpage.  I've posted my code below, but I'm a lost on what to do from here ... should I create a javascript object and assign the json values to the js object?  I think I need a little guidance on what to do next, here is what I have to far ...

<head runat="server">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">
    $.ajax({
        type:"GET",
        url: "WebMethods/GetTargets",
        data: JSON.stringify({}),
        success: function (data) {
            $("#datadisplay").append(data.d)            
        },
        error: function (result) {
            alert(result.responseText);
        }
    });
    </script>

    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="datadisplay"></div>
    </div>
    </form>
</body>

Open in new window


public static String strConnCallCenter = ConfigurationManager.ConnectionStrings["CallCenter"].ConnectionString;
     
   
        [WebMethod]
        [ScriptMethod]
        public static String GetTargets()
        {
            String qryTargets = "select * from dbo.t_Target where metric_id is not null";
            using(SqlConnection connCallCenter = new SqlConnection(strConnCallCenter))
            {
                using(SqlCommand cmdCallCenter = new SqlCommand(qryTargets, connCallCenter))
                {
                    String jsTargets = null;
                    DataTable dtTargets = new DataTable();
                    dtTargets.Load(cmdCallCenter.ExecuteReader());
                    DataSet dsTargets = new DataSet();
                    dsTargets.Tables.Add(dtTargets);                    
                    jsTargets = DataSetToJSON(dsTargets);
                    return jsTargets;                    
                }
            }  
        }

        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);
            }

            JavaScriptSerializer json = new JavaScriptSerializer();
            return json.Serialize(dict);
        }

Open in new window

Scarlett72Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
RobConnect With a Mentor Owner (Aidellio)Commented:
Hi,

so in my snippet, my object is objdata?
You look to be parsing it twice? Or is your webmethod returning a JSON object where one of the properties is a string you are wanting to parse (it may already get parsed when the ajax call is returned)?  Really hard to know without seeing what's happening
SO the easiest thing to do is to check what's coming back and we'll go from there.  Output the contents of what is returned to the console with console.dir(data.d);.  You can view the console by opening the developer tools in the browser you're using, you'll find it usually under tools in the menu.
i.e.
$.ajax({
        type:"GET",
        dataType: 'json',
        url: "WebMethods/GetTargets",
        data: JSON.stringify({}),
        success: function (data) {           
                    console.dir(JSON.parse(data.d));  //<========== outputs to the console
},
        error: function (result) {
            alert(result.responseText);
        }
    });

Open in new window


So if I want to reference the fields from my table to populate the object and then output to an html table what would be the best way to do that?
Definitely what you're doing by retrieving JSON is the first step.  Once you've got the data in your objdata variable then you can loop through it to create your table.  The best format is an array of JSON objects, e.g.
[{a: 1, b: 3}, {a: 3, b: 2}, {a: 8, b:3}, ...];

Open in new window


Then your javascript would look something like this:
assuming you already have an empty <table> element with say an id of 'mytable'
for (var i=0; i<objdata.length; i++) {
    $('#mytable').append('<tr><td>'+objdata[i].a+'</td><td>'+objdata[i].b+'</td></tr>');   
}

Open in new window

0
 
InsoftserviceCommented:
do you want to add values in ur already created json value.
Please elaborate little more if possible
0
 
RobOwner (Aidellio)Commented:
Assuming your webmethod returns the json data correctly then in the success function of your ajax call you'll have the object already in the data argument.  You should also add the dataType: 'json' to your ajax call as it will attempt to automatically parse the data response into a json object :

i.e.
$.ajax({
        type:"GET",
        dataType: 'json',
        url: "WebMethods/GetTargets",
        data: JSON.stringify({}),
        success: function (data) {
            $("#datadisplay").append(data.d)            
        },
        error: function (result) {
            alert(result.responseText);
        }
    });

Open in new window

0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Scarlett72Author Commented:
Hi Rob, so in my snippet, my object is objdata?
So if I want to reference the fields from my table to populate the object and then output to an html table what would be the best way to do that?

$.ajax({
        type:"GET",
        dataType: 'json',
        url: "WebMethods/GetTargets",
        data: JSON.stringify({}),
        success: function (data) {           
                    var objdata = JSON.parse(data.d);                     
},
        error: function (result) {
            alert(result.responseText);
        }
    });

Open in new window

0
 
Scarlett72Author Commented:
Hi Rob, I really appreciate you taking the time to help me with my understanding of this, I just want to take some time to work through it on my end and implement what you've given me, but will close and assign shortly.
0
 
RobOwner (Aidellio)Commented:
not a problem and please ask questions if you need me to clarify anything
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.