Quantcast
Channel: Recent Discussions — DataTables forums
Viewing all 81384 articles
Browse latest View live

DataTables warning (table id = 'tblRoles'): Requested unknown parameter '0' from the data source for

$
0
0

Hi,

I am getting below error while using datatable,
DataTables warning (table id = 'tblRoles'): Requested unknown parameter '0' from the data source for row 0

By code is below,

In aspx page,

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DataTables_Dot_Net2010.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <style>
        .widthFull
        {
            width: 100%;
        }
        .fontSize10
        {
            font-size: 10px;
        }
        .displayNone
        {
            display:none;
        }
    </style>
    <link href="Content/DataTables/css/demo_table_jui.css" rel="stylesheet" />
    <link href="Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="txtRoleName"></asp:TextBox><input id="btnSearch" type="button"  value="Search" style="width:65px;font-size: 11pt;" ></input>
    </div>
    <div>
        <table id="tblRoles" class="widthFull fontsize10 displayNone">
                <thead>
                    <tr>
                        <th>RoleID
                        </th>
                        <th>Role
                        </th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
    </div>
    </form>
    <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.23.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.json-2.3.min.js" type="text/javascript"></script>
    <script src="Scripts/DataTables/jquery.dataTables.js" type="text/javascript"></script>
    <script type="text/javascript" >

        $(document).ready(function () {
            $("#btnSearch").click(function (e) {
                getRoles();

            });
        });

        var getRoles = function () {

            $("#tblRoles").dataTable({
                "oLanguage": {
                    "sZeroRecords": "No records to display",
                    "sSearch": "Search on Roles"
                },
                "aLengthMenu": [[4, 25, 50, 100, 150, 250, 500, -1], [4, 25, 50, 100, 150, 250, 500, "All"]],
                "iDisplayLength": 4,
                "bSortClasses": false,
                "bStateSave": false,
                "bPaginate": true,
                "bAutoWidth": false,
                "bProcessing": true,
                "bServerSide": true,
                "bDestroy": true,
                "sAjaxSource": "WebService1.asmx/GetRoles",
                "bJQueryUI": true,
                "sPaginationType": "full_numbers",
                "bDeferRender": true,
                "fnServerParams": function (aoData) {
                    aoData.push({ "name": "roleName", "value": $("#txtRoleName").val() });
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    $.ajax({
                        "dataType": 'json',
                        "contentType": "application/json; charset=utf-8",
                        "type": "GET",
                        "url": sSource,
                        "data": aoData,
                        "success":
                                function (msg) {
                                    var json = jQuery.parseJSON(msg.d);
                                    fnCallback(json);
                                    $("#tblRoles").show();
                                }
                    });
                }
            });
        }
    </script>
</body>
</html>

In Webservice,

  [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        [WebInvoke(ResponseFormat = WebMessageFormat.Json,
         BodyStyle = WebMessageBodyStyle.Bare, Method = "GET")]
        public string GetRoles()
        {
            string outputJson = string.Empty;
            int sEcho = ToInt(HttpContext.Current.Request.Params["sEcho"]);
            int iDisplayLength = ToInt(HttpContext.Current.Request.Params["iDisplayLength"]);
            int iDisplayStart = ToInt(HttpContext.Current.Request.Params["iDisplayStart"]);
            string rawSearch = HttpContext.Current.Request.Params["sSearch"];

            string roleName = HttpContext.Current.Request.Params["roleName"];

            var numberOfRowsToReturn = "";
            numberOfRowsToReturn = iDisplayLength == -1 ? "TotalRows" : (iDisplayStart + iDisplayLength).ToString();

            string query = @"SELECT *
                            FROM
                                (SELECT row_number() OVER (ORDER BY RoleID ASC) AS RowNumber
                                        , *
                                    FROM
                                        (SELECT (SELECT count(Roles.RoleID)
                                                FROM
                                                    Roles) AS TotalRows
                                            , ( SELECT  count( Roles.RoleID) FROM Roles WHERE RoleID LIKE '%'+ @searchText +'%' OR Role LIKE '%'+ @searchText +'%' OR @searchText IS NULL ) AS TotalDisplayRows
                                            ,Roles.RoleID
                                            ,Roles.Role
                                        FROM
                                            Roles WHERE RoleID LIKE '%'+ @searchText +'%' OR Role LIKE '%'+ @searchText +'%' OR @searchText IS NULL) RawResults) Results
                            WHERE
                                RowNumber BETWEEN @StartIndex AND @NumberOfRows";

            DataTable dt = new DataTable();
            var sb = new StringBuilder();
            var totalRecords = "";
            var totalDisplayRecords = "";

            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["mainConnection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {

                    cmd.Connection = cn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = query;
                    cmd.Parameters.AddWithValue("@searchText", roleName);
                    cmd.Parameters.AddWithValue("@StartIndex", iDisplayStart + 1);
                    cmd.Parameters.AddWithValue("@NumberOfRows", numberOfRowsToReturn);

                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(dt);
                }
            }

            if (dt != null && dt.Rows.Count > 0)
            {
                totalRecords = dt.Rows[0]["TotalRows"].ToString();
                totalDisplayRecords = dt.Rows[0]["TotalDisplayRows"].ToString();
            }

            DataView dv = new DataView();
            DataTable dtNew = new DataTable();
            dv = dt.DefaultView;
            dtNew = dv.ToTable(true, "RoleID", "Role");

            outputJson = JsonConvert.SerializeObject(dtNew);

            sb.Clear();
            sb.Append("{");
            sb.Append(@"""sEcho"": ");
            sb.AppendFormat(@"""{0}""", sEcho);
            sb.Append(",");
            sb.Append(@"""iTotalRecords"": ");
            sb.Append(totalRecords);
            sb.Append(",");
            sb.Append(@"""iTotalDisplayRecords"": ");
            sb.Append(totalDisplayRecords);
            sb.Append(", ");
            sb.Append(@"""aaData"": ");
            sb.Append(outputJson);
            sb.Append("}");
            outputJson = sb.ToString();

            return outputJson;
        }

  public static int ToInt(string toParse)
        {
            int result;
            if (int.TryParse(toParse, out result)) return result;

            return result;
        }

My json is as below,

{"sEcho": "1","iTotalRecords": 10,"iTotalDisplayRecords": 10,
"aaData":
[
{"RoleID":1,"Role":"Admin"},
{"RoleID":2,"Role":"User"},
{"RoleID":3,"Role":"Manager"},
{"RoleID":4,"Role":"Affiliate"}
]
}

I am getting the error while executing the line fnCallback(json);

I reffer the below source having version vs2010

http://jquerydatatablessamp.codeplex.com/SourceControl/latest\

Please help me...

Thanks in advance...


hyperlink to website stored in 1 column

$
0
0

i have made a table of 10 columns in which 1 column displays website addresses. What i need is that when one clicks on those websites, it should be redirected to that website.Can you please help me on this

If you have an error 'Uncaught TypeError: Cannot read property 'nTr' of ...', this might fix it

$
0
0

I ran into this problem and traced it back to the stateSave and Load callback. The save posts form entries to a php backend. This backend stores it and the load callback retrieves it, but turns it into json. However, the PHP backend automatically saves everything as a string, so the start and length state properties came back in the json as :

"start": "0",
"length": "10"

the paging then said "01 to 010 of 98 results" and pressing 'next' triggered the error above, clicking on page 2 showed all results from 11 to 98.

The solution is to either fix the php save to store numbers as ints, or to fix in javascript in the load callback.

Ideally this should be fixed in the datatables code, in _fnLoadState,:

if ( s.start !== undefined ) {
settings._iDisplayStart = parseInt(s.start);
settings.iInitDisplayStart = parseInt(s.start);
}
if ( s.length !== undefined ) {
settings._iDisplayLength = parseInt(s.length);
}

I've posted this here for anyone running into the same issue.

Auke van Slooten
Muze.nl

(HTML5 export buttons) "Input fields" not export?

$
0
0

Hello, everyone ?

https://datatables.net/extensions/buttons/examples/html5/simple.html

I implemented it using the link above.

"Input fields" not export?

I've debugged Chrome

//////////////////////////////////////////////////////////

//<td class=" grid_data_c">Test Export</td> <------export OK!
// <td class=" grid_data_c">
// <input type="text" name="export" readonly="readonly" class="no_border w20" value="Test Export">
// </td> <------export Fail...

//////////////////////////////////////////////////////////

dataTables.buttons.js

Line number 1559

if ( config.stripHtml ) {
str = str.replace( /^\s+|\s+$/g, '');
}

Make it empty here.....

If not, is there another way?

Issues with moment.js and localization

$
0
0

Hi Allan,

I am using moment.js to format dates. I have included the MomentJS-2.13.0 Javascript. In addition I am using two locales:

<!--    Locales for moment.js-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/locale/de.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/locale/en-gb.js"></script>

To initialize moment.js I do this:

//Moment.js (date time) location settings
if (lang === 'de') {
    moment.locale('de');
} else {
    moment.locale('en-gb');
}
// Return today's date and time
var currentTime = new Date();

The Data Table uses this - and it works perfectly fine. For German (lang === 'de') it returns 'DD.MM.YYY' else it returns the English Version of 'DD/MM/YYY'.

{   data: "rfp.start_date",
    render: function ( data, type, row ) {
            return moment(new Date(data)).format('L');
    }
},

My problem is with Editor. The only thing that works here is the default unfortunately which correctly returns the current date in the German or English format.

fields: [ {
                label: "Start Date:",
                name:  "rfp.start_date",
                type:  "datetime",
                def:   function () { return moment(currentTime).format('L');},
                format: 'MM.DD.YYYY',
                opts:  {
                    showWeekNumber: true,
                    momentLocale: 'de'
                }
            }, {
                label: "End Date:",
                name:  "rfp.end_date",
                type:  "datetime",
                def:   function () { return moment(currentTime).format('L');}
            } ]

"Start Date" in this fashion only works for German because Editor forced me to hard code the format to be 'MM.DD.YYYY'. Editor does not accept the format 'L' which is a moment.js standard format used with localization. You can also see it in the respective moment locale scripts mentioned above. I tried to use a global variable predefined with one of the two formats but that produced an error. So how can I localize this? How can I preset the format so that is used correctly by Editor since it does not acceopt 'L'?

And there is another issue: Editor ignores "momentLocale: 'de'". "showWeekNumber" works however. For that reason my date picker is only in English and not shown in German.

Let's assume I get "momentLocale" working: How do I dynamically set the locale to either German or English?

"End Date" is even worse: Only the default works fine in German or English. Once you start editing the date it shows it in 'YYY-MM-DD'. For the German language setting it starts with the default of '03.02.2017'. Then I open the date picker which is in English only and if I select February 4th the date picker returns '2017-02-04' which is a problem ...

Please help!

Problem with Select2 and inline editing - possible bug?

$
0
0

Hi,

I've a problem with the Select2 plugin and inline editing. If I click the cell it shows the Select2 box with the search box focused as expected. However, if I click on the search box (or on any white space that isn't an option in the select) the datatables cell loses focus, the Select2 dropdown remains visible. Clicking on white space below the dropdown doesn't remove it and choosing an option doesn't update datatables.

I can't link to a live version right now but I've uploaded screenshots of a basic example, imgur.com/a/XHcYG.

I'm using the latest version of datatables, editor and 4.0.1 (and later) of Select2. I've stripped out all styles except of the base editor style and the Select2 style but hopefully you'll get the idea.

v1.6 .NET compilation issues

$
0
0

While upgrading my app from 1.5.6 to 1.6.0, I ran into some thorny compile-time bugs in the new DataTables .NET code. I fixed them, but would like to know whether others are seeing the same issue, or whether my hacks will break something else down the road. Here are the problems I encountered in Visual Studio Premium 2013.

In abstract class Query.cs, the following lines gave syntax errors:

        internal virtual string _bindChar => "@";
        internal virtual string[] _identifierLimiter => null;
        internal virtual string _fieldQuote => "'";

so I regressed them to the 1.5.6 code:

        // Copied from v1.5.6 to fix compilation errors
        virtual internal string _bindChar { get { return "@"; } }
        virtual internal string _identifierLimiter { get { return ""; } }
        virtual internal string _fieldQuote { get { return "'"; } }

In addition, in method void _Prepare(string sql), I had to change the vars left and right to strings to work with String.Join:

         // did not compile in line 1012) return left + String.Join(right + '.' + left, a) + right + alias;
         var left = idl[0];
         var right = idl[1];

         // fix
         var left = idl[0].ToString();
         var right = idl[1].ToString();

There was one other issue as well but I can't recall it now. I'll append if I remember it later. Thanks for any guidance.

Splitting MySql DATETIME type into spearate date and time

$
0
0

My MySql database has a DATETIME column. I need to display it in both the table list and in the bubble as separate date and time fields and in the case of new/update in the bubble, store them into the database as a DATETIME column,

Likewise, both date and time in the bubble need to have field appropriate drop down selectors.

Any thoughts, or better yet, examples.

Regards,
Jim


How to build a dropdown like a date selector

$
0
0

I have a field in the bubble that I need to provide a drop down similar to the date picker.

Assuming that the proposed drop down is in HTML and the javacsript/jquery code is available, how do I:

  1. detect and activate the dropdown when the field in the bubble is selected.

  2. structure/create/display the dropdown and handle input from the field and put data into the field.

Any thougnts, or better yet, examples.

Regards,
Jim

Display a large text field in the bubble as a scrollable container

$
0
0

I have a large text field in my database. I don't display it in the list but I do display it in the bubble and, of course, the bubble is unusable.

What I would like to do is either display it in the bubble as a scrollable unlimited textarea. of a specific size or cause a pop-up when the field is selected into and from which the text can be edited.

Any thoughts, or better yet, examples?

Regards,
Jim

Editor purchase - Usage questrion

$
0
0
  1. Upon purchase of the Editor, can I use it on two development machines. I have a desktop I use when home and a laptop I travel with. I keep them in sync with Git. Can I install and activate Editor on both or must I limit myself to using one machine or the other for development?

  2. Does the license extend to or is it required on the target web server?

Regards,
JIm

Individual Column Searching for Multiple values

$
0
0

Is there a way to use the Text Inputs to search for multiple values?

For example, I have a table that has a State column. Is there a way to do a search for both AL and AZ? Like typing "AL ,AZ" or "AL ; AZ"?

Here is how I'm initializing the Text Inputs:

api.columns('.dt-filter-text').every(function ()
{
    var that = this;

    $('input', this.footer()).on('keyup change', function ()
    {
        if (that.search() !== this.value)
        {
            that
              .search(this.value)
              .draw();
        }
    });
});

Styling Datatables with CSS - " content: '' "

$
0
0

Dear Datatables community,

I would like to style my data tables as follows:

@media screen and (max-width: 480px) {

#sample_1_previous a {
    content: "<";
}

#sample_1_next a {
    content: ">";
}

}

Sadly, this does nothing. The style is recognised by the browser though.

Is there a workaround or solution for this?

Error in finding dates on Server Side

Can't work out how to stop user being able to change the initial load order

$
0
0

I am using datatables to display a list of sales staff along with their monthly sales results and targets. I've got the tables set up so that when it initially loads it orders the data based on the grad total percentage column, which works fine. I can't get it to not allow a user to then change the sort order by clicking on the column headers. I donlt want anyone to be able to change the order of the table once it has initially loaded the data in and sorted it by the column I have set. The code I'm using is below.

$(document).ready(function() {
    var t = $('#myTable').DataTable( {
        "columnDefs": [ {
            "searchable": false,
            "orderable": false,
            "targets": 0,
            "rowReorder": false,
            "bFilter": false,
            "bPaginate": false,
            "bLengthChange": false,
        } ],
        "order": [[ 11, 'desc' ]],
        "bFilter": false,
        "bPaginate": false,
        "bLengthChange": false,
        "orderFixed": [ 11, 'desc' ],
        "rowReorder": false
    } );


    t.on( 'order.dt search.dt', function () {
        t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
            cell.innerHTML = i+1;
        } );
    } ).draw();
} );

Can anyone help me get this to work please?


datatables with details control : how to show details after refresh

$
0
0

Hello, I use datatables with details-control.
But, I would like to know how I can keep my selection.

For exemple :
I have 4 lines

  • LINE A
  • LINE B
    DETAILS LINE B
  • LINE C
  • LINE D
    DETAILS LINE D

And all the 5 minutes, I have a fonction for refresh my table
But I would like to keep open my details controls and my selection

Thanks you

This is my function

$('#table').dataTable(
{
'bProcessing' : true,
'bServerSide' : false,
'lengthMenu' : [ [ -1, 15, 30, 90 ],
[ "Tous", 15, 30, 90 ] ],
"order" : [ [ 1, "desc" ] ],
'sAjaxSource' : 'database/get_table.php',
"bAutoWidth" : false,
"stateSave" : true,
"aoColumns" : [ {
"className" : 'details-control',
"orderable" : false,
"defaultContent" : '',
"mData" : "",
"sWidth" : "5%"
}, {
"sName" : "",
"sWidth" : "95%",
"mData" : "id"
} ],
"fnDrawCallback" : function(settings) {
},
"fnRowCallback" : function(nRow, aData,
iDisplayIndex) {
if ($.inArray(aData["id"],
autogroupArray) !== -1) {
$(nRow).addClass('selected');
}
}
});

$('#table tbody').on(
'click',
'tr',
function() {
var tr = $(this).closest('tr');
var row = table.row(tr);

                            if (row.child.isShown()) {
                                if (row.data() !== undefined) {
                                    tableArray.unset(tableTable
                                            .cell(row.index(), 1).data());
                                    row.child.hide();
                                    tr.removeClass('shown');
                                }
                            } else {
                                if (row.data() !== undefined) {
                                    row
                                            .child(
                                                    format(row
                                                            .data().id))
                                            .show();
                                    tr.addClass('shown');

                                    tableArray.push(tableTable
                                            .cell(row.index(), 1).data());
                                }
                            }
                            if (row.data() !== undefined) {
                                $(this).toggleClass('selected');
                            }

                            Array.prototype.unset = function(val) {
                                var index = this.indexOf(val);
                                if (index > -1) {
                                    this.splice(index, 1);
                                }
                            };
                        });

KeyTable bootstrap stylesheet buggy in IE

Language, "decimal point is comma" not working

$
0
0

Hi Allan,
I am using this in the table default settings:

    //Data tables language settings
    if (lang === 'de') {
        showAllLabel = 'Alles anzeigen';
        $.extend( true, $.fn.dataTable.defaults, {
            "language": {
                "decimal": ",",
                "thousands": ".",
                "info": "Anzeige _START_ bis _END_ von _TOTAL_ Einträgen",
                "infoEmpty": "Keine Einträge",
                "infoPostFix": "",
                "infoFiltered": " - gefiltert aus insgesamt _MAX_ Einträgen",
                "loadingRecords": "Bitte warten Sie - Daten werden geladen ...",
                "lengthMenu": "Anzeigen von _MENU_ Einträgen",
                "paginate": {
                    "first": "Erste",
                    "last": "Letzte",
                    "next": "Nächste",
                    "previous": "Zurück"
                },
                "processing": "Verarbeitung läuft ...",
                "search": "Suche:",
                "searchPlaceholder": "Suchbegriff",
                "zeroRecords": "Keine Daten! Bitte ändern Sie Ihren Suchbegriff.",
                "emptyTable": "Keine Daten vorhanden",
                "aria": {
                    "sortAscending":  ": aktivieren, um Spalte aufsteigend zu sortieren",
                    "sortDescending": ": aktivieren, um Spalte absteigend zu sortieren"
                },
                //only works for built-in buttons, not for custom buttons
                "buttons": {
                    "create": "Neu",
                    "edit": "Ändern",
                    "remove": "Löschen",
                    "copy": "Kopieren",
                    "csv": "CSV-Datei",
                    "excel": "Excel-Tabelle",
                    "pdf": "PDF-Dokument",
                    "print": "Drucken",
                    "colvis": "Spalten Auswahl",
                    "collection": "Auswahl"
                },
                select: {
                    rows: {
                        _: '%d Zeilen ausgewählt',
                        0: 'Zeile anklicken um auszuwählen',
                        1: 'Eine Zeile ausgewählt'
                    }
                }
            }
        } );
    }
    //custom button added with language specific label
    $.fn.dataTable.ext.buttons.showAll = {
        text: showAllLabel,
        className: 'btn-showall-color hidden'
    };

Everything works except for

"decimal": ",",
"thousands": ".",

The mySql database field is defined as DECIMAL(15,2). A value of e.g. 60000 is shown in datatables as 60000.00 (as it is in a mySql workbench query). So the thousands point is missing and the decimal point is not converted to a decimal comma!
Any solution for this?

Update Search after table data change

$
0
0

Hello!

I use data tables for dynamic tables that are edited by users.

Typically I return search data to hidden <td>'s.

After the users edits the table I use ".html()" on the hidden TD's to update the data, but I see that this does not update the search function of DataTables. Searching for the old value still brings row.

Where is DataTables looking for it's search? Is there an object, or an element with data attached that I can update?

Can i place search data here after "initComplete" instead of hidden td's?

Fatal error call to a member function insertid ...

$
0
0

Same/similar error as reported here, but without using any joins: https://datatables.net/forums/discussion/39387/fatal-error-call-to-a-member-function-insertid-on-null. Full error:

PHP Fatal error:  Call to a member function insertId() on a non-object in /var/www/html/new/includes/editor/php/Editor/Editor.php on line 1601

Upgrading from Editor 1.5 to 1.6, haven't been able to pin down what's causing it yet. The referenced post had to do with Mjoin, which I'm not using. Trying to troubleshoot, but I don't think I can use the datatables debug area since it's server-side scripts.

Thoughts?

Viewing all 81384 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>