Solved

How do I pass a value from my jQuery DataTable row?

Posted on 2016-07-27
7
103 Views
Last Modified: 2016-09-30
How do I pass a value from my jQuery DataTable row, to my C# WebMethod? In the following code segment, when you hover over the checkmark / link image, there is a call made to a C# WebMethod, that returns a value which is used by an alert call to display some information (now, simply the DateTime presently for testing). I'd like to pass a specific value, from the current row, to use in that WebMethod to be processed and return a value to be used in that alert call. How do I do this?

<%@ Page Title="" Language="C#" MasterPageFile="MasterPageStock.master" AutoEventWireup="true" CodeFile="SignInGrid.aspx.cs" Inherits="SignInGrid" %>

<asp:Content ID="Content0" ContentPlaceHolderID="head" runat="Server">
    <style type="text/css">
        .divFade {
            display: none;
            position: absolute;
            overflow: hidden;
            z-index: 10000;
        }

        td.details-control {
            background: url('Images/bullet_add.png') no-repeat center center;
            cursor: pointer;
        }

        tr.shown td.details-control {
            background: url('Images/red_minus.png') no-repeat center center;
        }

        .navbar-right {
            display: block;
        }

        .lnkBtnLogOut, .pageTitle {
            display: inline;
        }

        .rwBtn {
            margin: 30px 0 0 0;
        }
    </style>

    <script type="text/javascript">
        //MYSQL DB VERSION
        $(document).ready(function () {
            $(".divFadeInOut").fadeToggle(4000);
            $.ajax({
                "url": "SignInGrid.aspx/getData",
                "type": "POST",
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                success: function (json) {
                    var table = $('#example').DataTable({
                        "columns": [
                            {
                                "className": "dt-body-center",
                                "targets": 0,
                                "data": "StudentID",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '">' + data + '</a>';
                                }
                            },
                            {
                                "className": "dt-body-center",
                                "data": "StudentName"
                            },
                            {
                                "className": "dt-body-center",
                                "data": "TimeIn"
                            },
                            {
                                "className": "dt-body-center",
                                "data": "TimeSignedIn"
                            },
                            {
                                "className": "dt-body-center",
                                "targets": 0,
                                "data": "StudentID2",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '&showweektotal=y" class="glyphicon glyphicon-ok text-center hovr-link" style="color: green;"></a>';
                                }
                            },
                            {
                                "className": "dt-body-center",
                                "targets": 0,
                                "data": "StudentID3",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '&signout=y" class="glyphicon glyphicon-time text-center" style="color: red;"></a>';
                                }
                            },
                        ],
                        "aaData": $.parseJSON(json.d)
                    });
                    //HERE IS WHERE THE MOUSEOVER CALLS MY WEB METHOD. HOW DO I PASS A SPECIFIC VALUE FROM MY ROW TO THIS???
                    $('body').on('mouseover', '.hovr-link', function (e) {
                        $.ajax({
                            type: "POST",
                            url: "SignInGrid.aspx/GetRecords",
                            data: "{}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (result) {
                                // Do something with records returned here
                                // Use result.d to get to JSON data
                                alert(result.d);
                            }
                        });
                    });

                    $('body').on('mouseout', '.hovr-link', function (e) {
                        $('div#pop-up').hide();
                    });
                }
            });

            var lblVal = $(".userIDLabel").html();
            var lblVal1 = $(".dealerTypeLabel").html();

            if (lblVal.indexOf("ADMIN") >= 0) {
                $(".adminLinks").css("display", "block");
                $("#liViewVendorSubmissions").css("display", "block");
                $("#liVendorList").css("display", "none");
                $("#topdropdown").css("display", "none");

                $("#liSearchInvintoryMenuItem").css("display", "none");
                $("#liRequstBoardMenuItem").css("display", "none");
                $("#liProfileMenuItem").css("display", "none");
                $("#liContactUsMenuItem").css("display", "none");
            }
            else {
                $(".adminLinks").css("display", "none");
            }
        });

        $(document).on('click', '#btnWeekTotal', null, function () {
            var url = this.getAttribute("data-url");
            alert(url);
            alert(window.location);
            window.location = url;

        });

        $(function () {
            var moveLeft = 0;
            var moveDown = 0;

            $('a#lnkweektotal').hover(function (e) {
                $('div#pop-up').show();
            }, function () {
                $('div#pop-up').hide();
            });

            $('a#lnkweektotal').mousemove(function (e) {
                $("div#pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
            });
        });
    </script>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
    <div class="row myRow">
        <div class="col-lg-12 text-page-title-center" style="background: #000; height: 33px;">
            <div id="divPageTitle" class="center-page-title center" runat="server">
                <asp:Label class="pageTitle" runat="server" ID="pageTitle" Text="SIGNED IN LIST"></asp:Label>
            </div>
        </div>
    </div>
    <table id="example" class="display responsive nowrap" data-page-length="10" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th class="dt-head-center dt-body-center" data-orderable="true">StudentID</th>
                <th class="dt-head-center" data-orderable="true">StudentName</th>
                <th class="dt-head-center" data-orderable="true">TimeIn</th>
                <th class="dt-head-center" data-orderble="true">TimeSignedIn</th>
                <th class="dt-head-center">Week Total</th>
                <th class="dt-head-center">Sign Out</th>
                <%--<th>Delete</th>--%>
            </tr>
        </thead>
    </table>
    <p>
        <a href="#" id="lnkweektotal">Show pop up</a>
    </p>
    <div id="pop-up" style="display: none;">
        <h3>Pop-up div Successfully Displayed</h3>
    </div>
        <div id="divFader" runat="server" class="col-xs12 divFade">
        <h4 id="H2" style="color: green;">
            <asp:Label runat="server" ID="lblUpdateConfMsg" Font-Bold="true" Font-Size="X-Large"></asp:Label></h4>
    </div>
</asp:Content>

Open in new window


C# WebMethod
    [WebMethod]
    public static string GetRecords()
    {
        return DateTime.Now.ToString();
    }

Open in new window

0
Comment
Question by:mikesExpertExchange
  • 4
  • 3
7 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41734234
Question
Line 83
"aaData": $.parseJSON(json.d)

Open in new window

You are requesting a JSON return in your AJAX call and then you do a parseJSON on the result - does not make sense.

Back to your query
Change your mouseover to this

$('body').on('mouseover', '.hovr-link', function (e) {
  // Get the <tr> parent so you can access the row data
  var parent = $(this).closest('tr');

  // Get access to the datatable
  var table = $('#example').DataTable();

  // Get the row data
  var data = table.row(parent).data();

// Dump to console to debug - REMOVE FOR PRODUCTION CODE
console.log(data);
  $.ajax({
    type: "POST",
    url: "SignInGrid.aspx/GetRecords",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
      // Do something with records returned here
      // Use result.d to get to JSON data
      alert(result.d);
    }
  });
});

Open in new window

In your event handler get the parent <tr>. Using the parent you can now use the dataTables .data method to access all the data in the row - returned as a JavaScript object so you can pick and choose which of the data items you want to use (or all of them as in the example above)
1
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41734813
@Julian Hansen: I'm new to this so I followed an example and when it worked I didn't know enough about it to know that part didn't make sense. What should that line be, to achieve the same results?

Also I put your code in place and it worked, up to the point of, in my C# WebMethod, what parameter/object should I now be taking in / passing to it?

I tried this:
    [WebMethod]
    public static string GetRecords(string StudentID)
    {
        return StudentID;
    }

Open in new window


but got this error:
{"Message":"Invalid JSON primitive: StudentID.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer
.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal
(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize
(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization
.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit
)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at
 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer
 serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData
, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
 context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

Open in new window

0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41734866
@Julian Hansen: Never mind, I figured out how to get my data! But thank you for your help! I'd still like to gain some insight as to what you mentioned above about it not making sense that I'm: "requesting a JSON object in my AJAX call, but then I'm doing a parseJSON on the result -" conceptually I not needing to do a thing, but the "why" of it is what I'm missing. Again, I'm new to this jQuery DataTable / AJAX / JSON thing so I'm sure I will make some mistakes, but any knowledge I can pick up along the way on my journey, I'd appreciate. I'll leave this open for a while to discuss further but you'll still get full credit for this. Thanks again.
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41754824
Apologies for the late response - I must have missed the notifications of your above two posts.

Your first question: What should that line be, to achieve the same results?

When you specify dataType: "json" in your AJAX call, JQuery will convert the return to JSON for you.

The only time you want to call parseJSON is when the returned data is in string format - i.e. has not been converted to a JSON object. As to what that line should be - I cannot say without knowing
a) What the return from the server is - if you do a
console.log(json)
in your success function and then post the results of the Response from your console (Press F12, select console and then expand the POST entry - click the Response tab and copy the content from there)
b) What the intended use case is of the aaData member

As to the why (your second post) here is a synopsis.

When you request data from the server you do so by sending a Request header - which includes any parameters you want to send as well as the method you are sending them (POST / GET). You can also send an HTTP header that specifies what format you expect the data to be returned as. When you add the
dataType: "JSON"
Member to your AJAX request you tell JQuery that the data you are getting back is in JSON format. JQuery then knows that it must do a parseJSON on the return before calling your success function.

If you left out the dataType property in your call and your server script did a JSON return then you would have to do parseJSON on the results - so it is an either or - in the first case JQuery does the work for you automatically - in the second you have to manually do the conversion.

I put together a sample for you to explain what is going on. You can access it here
If you open the console (F12) and click the Go button on the sample you should see some output in the console. If the checkbox is not checked you will see a JSON string (the return from the AJAX WITHOUT dataType JSON) followed by an Object - the result of calling $.parseJSON on the return.
If the checkbox is checked (dataType: JSON is set) then the first output will be an object - the native success return (JQuery auto parses the string) - and an error on the second output because we are calling $.parseJSON on an object not a string.

Source code for the key parts of the sample are as follows
HTML
  Set dataType:JSON <input type="checkbox" id="sendjson" /><br/>
  <button class="go btn btn-primary">Go</button><br/>

Open in new window

JQuery
<script>
$(function() {
  $('.go').click(function(e) {
    e.preventDefault();
    var params = {
      url: "sendsomejson.php",
      type: "post",
    }
    if ($('#sendjson:checked').length > 0) {
      params.dataType = "json";
    }
    $.ajax(params)
      .then(function(response) {
        console.log('This is what JQuery returns ... if checkbox is checked you see an object otherwise you see a string');
        console.log(response);
        console.log('Result of $.parseJSON - if checkbox is checked this should be an error');
        var x = $.parseJSON(response);
        console.log(x);
    });
  });
});
</script>

Open in new window

1
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41758369
Thank you for your input/insight on this.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41758493
You are welcome.
0
 
LVL 1

Author Closing Comment

by:mikesExpertExchange
ID: 41823935
Thank you.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
This article discusses how to create an extensible mechanism for linked drop downs.
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…

707 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

17 Experts available now in Live!

Get 1:1 Help Now