Link to home
Start Free TrialLog in
Avatar of Michael Sterling
Michael SterlingFlag for United States of America

asked on

Boolean logic in my initComplete

I need to add boolean logic into the initComplete api/method call for my jQuery DataTable so that when a session variable holds a certain value, it removes the "href" tag of the anchor tag in a specified column. I've got the following code in place:

            $.ajax({
                "url": "SignInGrid.aspx/getData",
                "type": "POST",
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                success: function (json) {
                    var table = $('#example').DataTable({
                        "initComplete": function (settings, json) {
                            $("#example tbody td:eq(0) a").removeAttr("href");
                        },
                        "columns": [
               .
               .
               .

Open in new window



but this removes the href attribute every time. I only need to to remove the href when the value of a certain Session variable is what I'm looking for.
Avatar of hielo
hielo
Flag of Wallis and Futuna image

The value of Session variables reside on the server.  Thus, you need to either:
a. Pass the Session value to the browser when the page is loading for the first time
OR
b. Request the value of the Session variable after the page has loaded.

Since you are doing an ajax request, option "b." seems more appropriate for your problem.  On line 6 you have success: function (json).  On the server you must be generating data for that json variable.  What you can do, is put the value of the Session variable that you want in that json variable/response as well.  For example, if you are currently sending an array of sports items/objects -ex:
[{"volleyball":1}, {"basketball":2}, {"football":3}]

Open in new window


(notice that in the example above there is no explicit label stating that the array is a "sports" list/array).  You would then need to restructure your response so that you can send your session name and value, and also you need to explicitly name the "sports" list/array:
{
"yourSessionVariableName": "theSessionVariableValue"
,"sports": [{"volleyball":1}, {"basketball":2}, {"football":3}]
}

Open in new window


If don't like the above approach or would rather keep the json variable strictly as an array, you can then just add the Session variable as either the first or last element of the array (it's up to you), but you have to remember to always remove it before processing the rest of the array.  Even if the session variable does not exist, you should still send a null value in its place. So, with this approach you would need to send:
[{"volleyball":1}, {"basketball":2}, {"football":3}, null]

Open in new window


Then on the browser side you have to remove that null item (since it is meant as the session value):
                success: function (json) {
                    var session_variable = json.pop();
                    var table = $('#example').DataTable({
                        "initComplete": function (settings, json) {
                            if( json_variable )
                            {
                                 $("#example tbody td:eq(0) a").removeAttr("href");
                            }
                        },

Open in new window

I am confused by your code - I am assuming this is a spin off of this question https://www.experts-exchange.com/questions/29081106/The-correct-CSS-selector.html where you added this code
            $.ajax({
                "url": "SignInGrid.aspx/getData",
                "type": "POST",
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                success: function (json) {
                    var table = $('#example').DataTable({
                        "initComplete": function (settings, json) {
                            $("#example tbody td:eq(0) a").removeAttr("href");
                        },
                        "columns": [

Open in new window

Why are you calling AJAX directly - instead of using the DataTables ajax property to set the URL of your data?
Avatar of Michael Sterling

ASKER

@Julian: The short answer is that I'm new to using DataTables/AJAX/JSON and at the time that I built this page, I just needed to understand it far enough to make it work. If there's a better way, I'm open to it, however I'm new to this.
@hielo: This is how I'm getting my data currently, how do I fit your suggestion(?) into my scenario?

    /// <summary> ****************
    /// getData                  *   
    /// </summary> ***************
    [WebMethod]
    public static string getData()
    {
        #region MYSQL VERSION

        MySqlConnection con;
        MySqlDataReader dbr;
        MySqlCommand cmd;
        Utility utl = new Utility();

        string strSelect = "";
        string strBody = "";
        string erroBody = "";

        List<InOutTable> data = new List<InOutTable>();
        strSelect = @"SELECT * FROM trackerdata.utinout WHERE TimeOut IS null ORDER BY TimeIn ASC";

        using (con = new MySqlConnection())
        {
            try
            {
                con.ConnectionString = ConfigurationManager.AppSettings["ConnStringMySQL"].ToString();
                con.Open();

                cmd = new MySqlCommand(strSelect, con);
                dbr = cmd.ExecuteReader();

                while (dbr.Read())
                {
                    InOutTable inoutrec = new InOutTable();

                    inoutrec.StudentID = dbr["StudentID"].ToString();
                    inoutrec.TimeIn = dbr["TimeIn"].ToString();
                    inoutrec.StudentName = dbr["StudentName"].ToString();
                    inoutrec.TimeSignedIn = CalculateTime(Convert.ToDateTime(dbr["TimeIn"].ToString()), dbr["StudentID"].ToString());
                    inoutrec.StudentID2 = dbr["StudentID"].ToString();
                    inoutrec.TimeRecID = dbr["InOutUid"].ToString();
                    data.Add(inoutrec);
                }

            }
            catch (MySqlException ex)
            {
            }
        }

        #endregion

        System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string aaData = jSearializer.Serialize(data);
        return aaData;
    }

Open in new window


and this is the ajax method that assigns data to my table in the markup

            $.ajax({
                "url": "SignInGrid.aspx/getData",
                "type": "POST",
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                success: function (json) {
                    var table = $('#example').DataTable({
						"order": [3, 'asc'],
                        "columns": [
                            {
                                "className": "dt-body-center std-id",
                                "targets": 0,
                                "data": "StudentID",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a id="std-id" class="std-id" 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 id="' + data + '" href="StudentAthleteInfo.aspx?StudentID=' + data + '&showweektotal=y" class="glyphicon glyphicon-ok text-center hovr-link hidden-xs hidden-sm hidden=md" style="color: green;"></a>';
                                }
                            },
                            {
                                "className": "dt-body-center",
                                "targets": 0,
                                "data": "TimeRecID",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="SignInGrid.aspx?TimeRecID=' + data + '&signout=y&UserStatus=' + lblVal + '" class="glyphicon glyphicon-time text-center" style="color: red;"></a>';
                                }
                            },
                        ],
                        "aaData": $.parseJSON(json.d)
                    });

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe 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
This  worked like I needed it to.