Solved

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

Posted on 2015-01-05
6
1,169 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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
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…

747 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

12 Experts available now in Live!

Get 1:1 Help Now