Link to home
Start Free TrialLog in
Avatar of Scarlett72
Scarlett72

asked on

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

Avatar of Insoftservice inso
Insoftservice inso
Flag of India image

do you want to add values in ur already created json value.
Please elaborate little more if possible
Avatar of Rob
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

Avatar of Scarlett72
Scarlett72

ASKER

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

ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
not a problem and please ask questions if you need me to clarify anything