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

jQuery Ajax to DataTables Ajax

$
0
0

Hi, I'm looking to convert my jQuery ajax table code to dataTables so I can use things like reload etc

Im stuck on how I would send the variables (the POST data) to the controller to get the data for the table back.

My current code:

$(document).ready(function() {
    var token = '<?php echo json_encode($token); ?>';
    var getUserComments = true;
    var usereid = '<?php echo $_SESSION['exid']; ?>';
    // Get Data from Database and Populate the DataTable
    $.ajax({
        url: 'controllers/recipeControl.php',
        method: 'post',
        dataType: 'json',
        data: { getUserComments: getUserComments, usereid: usereid, token: token },
        success: function(data) {
            var table = $('#datatable').dataTable({
                order: [[ 2, "desc" ]],
                responsive: true,
                data: data,
                select: false,
                "columnDefs": [
                    { "orderable": false, "targets": 3 }
                ],
                columns: [
                    
                    { 'data': 'recipe_comment_recipe_name', 
                        "render": function ( data, type, row, meta ) {
                            if(row.batch_recipe_url === '') {
                                recipeLink = data;
                            }
                            else {
                                recipeLink = "<a href='recipe/" + row.recipe_comment_recipe_id + "'>" + data + '</a>';
                            }
                            return recipeLink;
                        },
                    },
                    { 'data': 'recipe_comment', 
                        "render": function ( data, type, row, meta ) {
                            return data;
                        },
                    },
                    { 'data': 'recipe_comment_date', 
                        "render": function ( data, type, row, meta ) {
                            if (type == "sort" || type == 'type')
                                return data;
                                // Create date from input value
                                var inputDate = new Date(data);

                                
                                // Get today's date
                                var todaysDate = new Date();
                                //var date = (moment(data).format("ddd DD/MM/YYYY HH:mm:ss"));
                                // call setHours to take the time out of the comparison
                                if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
                                    var d = new Date(data);
                                    var hour = d.getHours();
                                    var minute = ('0'+d.getMinutes()).slice(-2);
                                    return 'Today ' + hour +':'+ minute;
                                }else {
                                    return (moment(data).format("ddd DD/MM/YYYY HH:mm:ss"));
                                }
                        }
                    },  
                    { 'data': 'actions',
                        "render": function ( data, type, row, meta ) {
                            return "<button type='button' class='btn btn-primary recipeCommentEdit' href='#'>Edit</button><button class='btn btn-primary delete' type='button'>Delete</button>";
                        }
                    }],
            });
        }
    })
})

Column visibility control is not working for Me

$
0
0

I am trying to add Column Visibility Control to my Datatable. but when I add it I am not able to see anything.

       var dataTable = $('#employee-grid').DataTable( {
            "processing": true, 
            "oLanguage": { "sSearch": "Search:" },
            "bJQueryUI": true,
            "bDestroy": true,
            "bPaginate": true,
            "bLengthChange": true ,
            "bFilter": true,
            "bSort": true,
    "lengthMenu": [[10, 25, 50, 100, 200, -1], [10, 25, 50, 100,200, "All"]],
            "bInfo": true,
            "bAutoWidth": false,
            "bDeferRender": true,
            "bRetrieve": true,
           " bSelect": true,
           // "smart": true,
            "sPaginationType": "full_numbers", 
     responsive: {
             details: {
             type: 'column',
             className:'control',
          target: 1
              }     
              },


             order:[],
             columnDefs: [ {
             className: 'control',
             orderable: false,
             targets:   1   
             },
             {
              orderable: false,
              targets:   0  
              },        
      ],
         fixedColumns: true,

              "sAjaxSource":"assets/ajax/contact_list-load.php",

     dom: 'lBfrtip',

             buttons: [
                             {
                              extend: 'copyHtml5',          
                              exportOptions: {
                               columns: [2,9,10,11,12,15,14,13,16,23,17,18,19,20,21,22,24]
                               }
                               },
                              {
                              extend: 'excelHtml5',
              text: 'XLS',
                              exportOptions: {
                               columns: [2,9,10,11,12,15,14,13,16,23,17,18,19,20,21,22,24]
                              }
                              },
                  {
                      extend:  'csvHtml5',
                  exportOptions: 
                  {
               columns: [2,9,10,11,12,15,14,13,16,23,17,18,19,20,21,22,24]
                   }
                   },
                          ],
                   //if add here  'colvis' i am not able to see anything just showing column names
                      }  );

Getting Error DataTables warning: table id=employee-grid - Invalid JSON response

$
0
0

I am Getting Error Invalid JSON I am Showing Address, CompanyName, Street In Datatable And for some users, there are German, French Characters.
while showing it in Datatable its Getting Invalid JSON.

I don't know why it is throwing Error for Non-ASCII Characters ??

data-priority: Responsive Button missing if first column is collapsed

$
0
0

I'm using datatables together with it's responsive extension. Everything works as expected except setting the Priority of columns.

<tr> <th>Name</th> <th data-priority="1">Position</th> <th>Office</th> </tr>

If now the viewport is so small, that one column (Office) is collapsed. There is a plus-sign appearing as expected.
But if there is still to less space so two columns are collapsed (Name and Office - because Position stays the longest), then the plus-sign disappears together with column 'Name'.

If think this is because of the CSS first-child-selector in the responsive extension:

table.dataTable.dtr-inline.collapsed > tbody > tr[role="row"] > td:first-child:before,
table.dataTable.dtr-inline.collapsed > tbody > tr[role="row"] > th:first-child:before {
top: 9px;
left: 4px;
height: 14px;
width: 14px;
display: block;
position: absolute;
color: white;
border: 2px solid white;
border-radius: 14px;
box-shadow: 0 0 3px #444;
box-sizing: content-box;
text-align: center;
text-indent: 0 !important;
font-family: 'Courier New', Courier, monospace;
line-height: 14px;
content: '+';
background-color: #31b131;
}

See example here: http://live.datatables.net/wokovivo/1/edit

Does anybody have an idea for a workaround or how to fix this so the plus-sign is not missing on small screens?

Thanks,
miman

How to set value for a calculated cell without submitting?

$
0
0

Hi.

I have some cells that do not have data in the ajax source. I dynamically calculate and display them through a custom rendering function. I need to update it on the fly while the user is in inline mode and he/she presses a key in a specific field. I tried to use editor.field('field').val('new calculation?') (like in here: https://datatables.net/forums/discussion/46864) But it didn't work.

Actually I don't even have a field initiated, because as I said, it's an on-the-fly value by calculation. I just tried field().val() just to test if things work; as well as table.cells(). But I am stuck here now.

{data: price, render: numberRendering}
{name: 'percentage', data: null, render: customRenderer}

I would like to update the value of percentage cell, without submitting, by just using an event listener like;

$(editor.field('price').input()).on('keypress', function (e, d) {
  // What now?
}

Error type mData

$
0
0

Hello i have a problem with Datatables i try to link my code but is it impossible
i have this error

Uncaught TypeError: Cannot read property 'mData' of undefined
at HTMLTableCellElement.<anonymous> (jquery.dataTables.min.js:89)
at Function.each (jquery.js:354)
at jQuery.fn.init.each (jquery.js:189)
at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:89)
at Function.each (jquery.js:354)
at jQuery.fn.init.each (jquery.js:189)
at jQuery.fn.init.m [as dataTable] (jquery.dataTables.min.js:82)
at jQuery.fn.init.h.fn.DataTable (jquery.dataTables.min.js:164)
at HTMLDocument.<anonymous> (info_bdd:252)
at mightThrow (jquery.js:3534)
``
sorry is impossible to link my code i have error "Body is 15116 characters too long."

i don't understand why function a datatable forum... my code is very long

Delete doesn't work with a tablename using the alias. Alias is required for server-side processing.

$
0
0

IMHO there is a bug in the _remove_tables method of Editor leading to an issue when deleting a row from the aliased table. If an alias is set used " as " word Editor object stores the tablename in a row of the $_table array. But the problem is that it's store "as it is".

Example: Editor::inst( "test", "test_Table as test_alias", array("a","b", "c") );
object that will be create will have
_table as array of [0] => "test_Table as test_alias".

When trying to delete the row _remove_table method is called and it tried to look for a tablename of the row being deleted in the _table. It fails because table name that comes from dbField is alreaty aliased and shows test_alias that doesn't match _table[0].

Has anyone met the same issue?

KR
Jacek

La info de datatables no es responsive

$
0
0

Hola, cuando hago la tabla responsive, la info sobresale mucho de la tabla y provoca scroll horizontal. Como lo puedo arreglar.


ColVis problem during datatables created in javascript

$
0
0

I've a datatable created only by javascript. (I've to create in this way... json data rows also is created in this way due to program limitation)

Construction work well, but there's a problem using ColVis:

If I hide, for example "STATO" column, then I want to show again...it pulls up at the end of the table!

This is my fiddle: http://jsfiddle.net/bbLjzspf/4042/

Why "searchable: false" erase the data of the column?

$
0
0

Hi there,

I've this column settings:

columns: [
    ...
    { data: "ClinicID", title: "", visible: false, searchable: true },
    ...
]

I hidden the field, and I want to keep the value within it (because I use as pivot for other searches; i.e. its related to other data).
But:

  • if I set searchable: true and I insert the ID, it filters also for that column on a Search input field (for example).
  • if I set searchable: false, it empty the value, so I can't use it as pivot anymore.

What should I do?
Thanks

Bootstrap 4.1.1 / Select2 4.0.5 / Editor.select2 / Datatables 1.10.16

$
0
0

Hello all,

Fairly new to Datatables and the Editor and I am trying to determine what is going on with my Editor. Here is a .Gif of the issue. As you can see, the cursor is above the input element.

I am using:
Bootstrap 4.1.1
Select2 4.0.5
Editor.select2
Datatables 1.10.16 (Complete bundle from the builder)

I do not have any customized .css but I am trying to use Select2 to populate my Editor.

Has anyone run across this before? Any guidance would be most appreciated!

Kind Regards,
Jason

Differents format dates for input hidden and input date

$
0
0

Hi, Allan. How can I capture the date in a hidden field, but capture the full date, since at the current time I am capturing only in the format yyyy-mm-dd, but need to capture in the format yyyy-mm-dd HH: mm: ss without changing the original field, ie in the hidden field capture the full date and in the original field continue with the same format?

Issue with Scroller and scrollTo()

$
0
0

Using the scrollTo() function causes an alert that says "Pagination is required in order to use Scroller", yet in the examples scrollY is set to true. The whole point of the scrollTo() is to 'scroll to' the row index, so how is this alert possible?

how to choose data for tooltip

$
0
0

Hi,

I'm using datable with json data. I would like to add a tooltip with an information presents ('description') in my json.
How it's possible ? my tooltip always display the same data presents in the row (in my case the 'name' not the 'description').

My code :

$("#referenceTable tbody").empty();

var currentObject = $('#SelectObject').val();
table = $('#referenceTable').dataTable( {
    data : json,
    columns: [
        {"data" : 'id'},
        {"data" : 'Client'},
        {"data" : 'type_object'},
        {"data" : 'name'}            
    ],
    columnDefs: [
        { width: 50, targets: 0 },
        { width: 150, targets: 2 },
        { "data": 'description',
          "render": function (data, type, full, meta) {
            return '<span data-toggle="tooltip" title="' + data + '">' + data + '</span>';
        },
        "targets":3
     }

....

$('#referenceTable').on('draw.dt', function () {
    $('[data-toggle="tooltip"]').tooltip();
});

Thanks in advance ;-)

Navigation blocked during ajax request

$
0
0

Hi all,
When my datatable is fetching data from server with ajax, I can not navigate through hypertext links. It waits until the datatable finishes loading. This is not the normal behaviour, and I don't remember if it was explicitly set. I could not figure out why? Is there any flag that needs to be enabled/disabled? which flag/option can I debug?

This is my config:

const DEFAULT_OPTIONS = {
  ajax: {
    url: '',
    async: true,
    cache: true,
    type: 'GET',
    dataType: 'json',
    beforeSend: (xhr, settings) => {
      // xhr.setRequestHeader('Authorization', 'bearer *********')
    },
    // handle data to be sent to server
    data: (data, settings) => {
      // cancel previous request if exists
      if (settings.jqXHR) {
        settings.jqXHR.abort()
      }
      let _data = {}
      if (typeof data.start !== 'undefined' && typeof data.length !== 'undefined') {
        _data.limit = data.length
        _data.page = (data.start / data.length) + 1
      }
      // set column order
      if (typeof data.order === 'object' && data.order.length > 0) {
        let colNum = data.order[0].column
        let attrName = settings.aoColumns[colNum].data
        _data[`order[${attrName}]`] = data.order[0].dir
      }
      // set search value
      if (data.hasOwnProperty('search') && data.search.value !== '') {
        _data['search'] = data.search.value
      }
      return _callbacks.buildQuery(_data, settings)
    },
    // handle response
    dataFilter: (data, settings) => {
      return _callbacks.buildResult(data, settings)
    },
    error: () => {
      Alert.error('Error !', 'Unable to fetch data for content', 0)
    }
  },
  dom: `<'row'<'col-sm-6'i><'col-sm-2'l><'col-sm-4'p>>
  <'row'<'col-sm-12'tr>>
  <'row'<'col-sm-12'p>>`,
  language: i18nConfig[context.locale],
  bSortCellsTop: true,
  processing: false,
  serverSide: true,
  displayLength: 10,
  lengthMenu: [10, 15, 25, 30, 40, 50, 75, 100],
  responsive: true,
  paging: true,
  lengthChange: true,
  searching: false,
  ordering: true,
  info: true,
  autoWidth: false,
  destroy: true,
  oClasses: {
    sLengthSelect: 'form-control selectpicker btn-sm'
  },
  preDrawCallback: (settings) => {
    let $tableWrapper = $(settings.nTableWrapper)
    let $select = $tableWrapper.find('.selectpicker')
    $select.attr('data-style', 'btn-sm').attr('data-width', 'fit')
    $select.selectpicker()
  }
}


Editor: optional field from joined table (OUTER JOIN)

$
0
0

I am using Editor and struggling with one text field from a side table that I want to be optional, like in an OUTER JOIN. (I am using MySQL.) I've found a few other threads on that topic here, but those situations seem more complex than my issue. I have set my side_table.id to be an auto-increment, primary index. I have set the main_table.notes field as NULL (yes), and it should get the value of the side_table.id field or remain null if there is no corresponding row in the side_table.

The following javascript code produces an SQL error saying that whatever text I attempted is an incorrect integer value for the field 'notes.' Here is the actual text that appears in red on my Editor form: "An SQL error occurred: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'This is a note.' for column 'notes' at row 1"

{ label: 'Notes',   name: 'main_table.notes',  type: "textarea"},     // Produces SQL error

I thought about switching the name part of the javascript to the side_table, but when I do no error is returned but main_table.notes remains a null value:

{ label: 'Notes',   name: 'side_table.note_text',  type: "textarea"},    // No error, but no value in main_table.notes field

I think that my server script code is correct:

server script:

       Field::inst( 'main_table.notes')    // main_table.notes is an integer
            ->options( options::inst()
                ->table( 'side_table')
                ->value( 'id') 
                ->label( 'note_text')
            ),
        field::inst( 'side_table.note_text'),

server script join clause:

->leftJoin( 'side_table', 'side_table.id', '=', 'main_table.notes')

As a test, I manually entered a single record into the side table causing its id field to equal 1, and in the main table I modified the 'notes' integer field to equal 1 for an existing record. The text field now displays properly in my Table and in my Editor form. I just can't enter a the note using the Editor form either by 'edit' or by 'new.'

I don't need a 1-to-many relationship because for any main_table record, I would only need one corresponding notes record in the side table.

Does anyone have just a basic example of how to do this? I realize that I could just keep the text (notes) in my main table, but I would like to learn how to do it this way just so I know how it can be done.

highlight search field by having the focus

$
0
0

I would like that when I click on a field in the table and this field appears in the table search, this search engine will be highlighted in some way, changing the color for example

"initComplete": function (settings, json) {//Hace una busqueda haciendo click sobre el campo
                var api = this.api();
                api.$('td').not(" :nth-child(1),:nth-child(7), :nth-child(9)").click(function () {
                    $( ".input" ).css( "border", "3px solid red" );
                    api.search(this.innerHTML).draw();
                });
            },

Editor: Field disappears after focus is lost, and appears when focused

$
0
0

I have one field that when the user inserts a value, the value is checked from the database, and if the value is valid, it automatically sets the value for the next field.

Next field is set using:
datatable.cell(row, 3).data(value);

The cell value is set correctly, but after it looses the focus, the value disappears.
And when it receives the focus, it appears again.

Please see the following video, it will show a live example: https://meocloud.pt/link/7a7fc072-d964-481f-affd-b1548495a59b/Editor.mkv

There is nothing in the code that can cause this, and i'm totally baffled.
Any idea on what can cause this problem, or how to avoid it?

Empty table filled by search button (ajax) with paging - Bootstrap 4

$
0
0

Good morning.
A little stuck. We have a current implementation shown below using the old version of DataTables.
The page has a number of entries a user can choose from and then click 'Search'.
The createTable() function calls a web service with the combined search criteria and paging/search information.
On return, a .dataTable() is created an returned to the screen.

Issues:
1) old implementation, would like to switch to .ajax
2) because the #tbl isn't instantiated as a .DataTable on page load, Bootstrap 4 css is not applied correctly

Really smart folks on this forum. Any help would be greatly appreciated.

Current implementation

<!--html-->
<!-- numerous searching criteria -->
<input type="button" id="SearchButton" class="btn btn-success btn-sm" value="Search" />
<table id="tbl" class="table table-bordered table-condensed table-striped table-hover"></table>

<!--script-->
$('#SearchButton').on('click', function () {
     createTable();
});

// Paged Table Functions
function getTableData(page, sortColumn, sortDirection) {
        var dfd = $.Deferred();
        var pageSize = $('[name=tbl_length]').val();
        var search = $('#tbl_filter label input').val() ? $('#tbl_filter label input').val() : null;
        var startdate = $('#StartDate').val() === '' ? '1/1/1900' : $('#StartDate').val();
        var enddate = $('#EndDate').val() === '' ? '1/1/3000' : $('#EndDate').val();

        var data = {
            FacilityId: $('#FacilityId').val(),
            UserId: $('#UserId').val(),
            RequestedBy: $('#ProfileUserId').val(),
            StartDate: startdate,
            EndDate: enddate,
            Keyword: $('#Keyword').val()
        };

        var searchParams = {
            Search: search,
            Page: page,
            PageSize: pageSize,
            SortColumn: sortColumn,
            SortDirection: sortDirection
        }

        $.extend(data, searchParams);

        $.ajax(url, {
            type: 'Post',
            data: JSON.stringify(data),
            dataType: 'text',
            contentType: null,
            cache: false,
            success: function (result) {
                try {
                    dfd.resolve(JSON.parse(result));
                } catch (ex) {
                    dfd.resolve(result);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                dfd.reject(jqXHR, textStatus, errorThrown);
            }
        });

        return dfd.promise();
}

function createTable() {
        var entryId;

        var optionalSettings = {};

        var columns =
            [
                { title: 'No.', data: 'Number', render: function (data, type, row) { return '<a href="/Main/Controller/View/' + row.EntryId 
                        + '">' + data + '</a>' } },
                { title: 'Name', data: 'Name', 'class': 'text-nowrap', render: function (data) { return data } },
                { title: 'Date', data: 'Date', 'class': 'text-center', render: function (data) { return data } },
                { title: 'Location', data: 'Location', 'class': 'text-nowrap', render: function (data) { return data } },
        ];

        createPagedTable('#tbl', columns, optionalSettings, 3, 'desc', getTableData);

}

function createPagedTable(selector, columns, optionalSettings, sortColumnIndex, sortDirection, fnGetData) {

        if (!sortColumnIndex) sortColumnIndex = 0;
        if (!sortDirection) sortDirection = 'asc';

        var tableSettings = {
            "dom": 'Rlfrtip',
            "processing": true,
            "serverSide": true,
            "language": {
                "infoFiltered": ""
            },
            "fnDrawCallback": function () {
                $("[rel='tooltip']").tooltip();
            }
        }

        // Optional Settings
        $.extend(tableSettings, optionalSettings || {});

        // Add Columns
        $.extend(tableSettings, {
            "order": [[sortColumnIndex, sortDirection]],
            "aoColumns" : columns
        });

        // Add Get Data Function
        $.extend(tableSettings, {
            "fnServerData": function (sSource, aoData, fnCallback) {
                var page = aoData[3].value;
                var sortColumn = columns[aoData[2].value[0].column].mData;
                var sortDirection = aoData[2].value[0].dir;

                fnGetData(page, sortColumn, sortDirection).then(function (data) {
                    fnCallback({
                        "iTotalRecords": data.length < 1 ? 0 : data[0].TotalRows,
                        "iTotalDisplayRecords": data.length < 1 ? 0 : data[0].FilteredTotalRows,
                        "aaData": data
                    });
                });
            }
        });

        if (!$.fn.DataTable.isDataTable(selector)) {
            pagedTable = $(selector).dataTable(tableSettings);
        } else {
            pagedTable.fnDraw();
        }

        return pagedTable;
}

Question about using 'select2' field plugin

$
0
0

Hi,

I am trying to use 'select2' field plugin to achieve 'multi-select' dropdown box. I have the following sample JSON data:

"data": [
{
"DT_RowId": "row_1",
MonthlyCost: 1000,
MonthlyImpressions: 10000,
Zone: [{
Id: 1,
name: "Zone1"
},
{
id: 2,
name: "Zone2"
}
]
},
{
"DT_RowId": "row_2",
MonthlyCost: 100,
MonthlyImpressions: 100,
Zone: [{
Id: 1,
name: "Zone1"
},
{
id: 2,
name: "Zone2"
},
{
id: 3,
name: "Zone3"
}
]

}

]

I am trying to list zone using 'select2' field type with multi-select option. The following code does not work.
{
label: "DMA/Zone: ",
name: "Zone[].id",
"type": "select2",
"opts": {
"multiple": "multiple",
"allowClear": true,
},
}

In addition, I may need to display zones in groups. I know you mentioned using 'children' properties. Can you give me an example? In this case, for example, I need to group 'zone1' and 'zone2' together. How do I do that?

Thank you very much for your help!

Jerry

Viewing all 82258 articles
Browse latest View live


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