Solved

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

Posted on 2015-01-05
6
1,344 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
  • 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 42

Expert Comment

by:Rob Jurd, EE MVE
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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 42

Accepted Solution

by:
Rob Jurd, EE MVE earned 500 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 42

Expert Comment

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

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jQuery Validate 4 36
how can i count words? 2 40
What am I doing wrong with this Lightbox widget? 6 33
how can i test my code? 1 33
In order to have all security and back ups taken care of, WordPress users can sign up for services with WP Engine.
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
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…

813 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now