?
Solved

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

Posted on 2015-01-05
6
Medium Priority
?
1,690 Views
Last Modified: 2015-01-12
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

0
Comment
Question by:Scarlett72
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 15

Expert Comment

by:Insoftservice
ID: 40532926
do you want to add values in ur already created json value.
Please elaborate little more if possible
0
 
LVL 43

Expert Comment

by:Rob
ID: 40534822
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
 

Author Comment

by:Scarlett72
ID: 40541250
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 43

Accepted Solution

by:
Rob earned 2000 total points
ID: 40541307
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
 

Author Comment

by:Scarlett72
ID: 40541467
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
 
LVL 43

Expert Comment

by:Rob
ID: 40541472
not a problem and please ask questions if you need me to clarify anything
0

Featured Post

2017 Webroot Threat Report

MSPs: Get the facts you need to protect your clients.
The 2017 Webroot Threat Report provides a uniquely insightful global view into the analysis and discoveries made by the Webroot® Threat Intelligence Platform to provide insights on key trends and risks as seen by our users.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In order to have all security and back ups taken care of, WordPress users can sign up for services with WP Engine.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question