grails,datatables,datatables-1.10,grails-2.4 , How to update a server side datatable on change a checkbox from outside of datatable


How to update a server side datatable on change a checkbox from outside of datatable

Question:

Tag: grails,datatables,datatables-1.10,grails-2.4

I am using data table with Grails. I have a check box outside the data table and on its event I want to load the table again with the check box value. Here are my attempts below :

In my view where the check box is >>

<g:checkBox id="wrapCheck" name="wrapCheck"/> Wrapped

Here is my attempts in view where I am calling server method >>

$('#wrapCheck').on('click', function (e) {
    setWrapActiveStatus();
    var referenceId = $('#callForWrap').val();
    jQuery.ajax({
        type: 'POST',
        dataType: 'JSON',
        url: "${g.createLink(controller: 'androidGame',action: 'ajaxAndroidGameList')}?wrapCheck=" + referenceId,
        %{--url: "${g.createLink(controller: 'androidGame',action: 'ajaxListByWrapActiveStatus')}?wrapCheck=" + referenceId,--}%
        success: function (data, textStatus) {
            if (data.isError == false) {
                $('#example').DataTable().ajax.reload();
            } else {
                alert(data.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
});

here is my setWrapActiveStatus() function >>

function setWrapActiveStatus(){
    if($("#wrapCheck").prop('checked') == true){
        $('#callForWrap').val("1");
    }else{
        $('#callForWrap').val("");
    }
}

And here is my Controller Action >>

def ajaxAndroidGameList() {
    LinkedHashMap gridData
    String result
    LinkedHashMap resultMap = androidGameService.androidGamePaginateList(params)
    if(params.wrapCheck == "1"){
        resultMap = androidGameService.androidGamePaginateListByWrapStatus(params)
    }

    // LinkedHashMap resultMap = androidGameService.androidGamePaginateList(params)

    if(!resultMap || resultMap.totalCount== 0){
        gridData = [iTotalRecords: 0, iTotalDisplayRecords: 0, aaData: []]
        result = gridData as JSON
        render result
        return
    }
    int totalCount = resultMap.totalCount
    gridData = [iTotalRecords: totalCount, iTotalDisplayRecords: totalCount, aaData: resultMap.results]
    result = gridData as JSON
    render result
}

My action is response well only wrapped list but data table does not update.

EDIT - Data table Initialization

$('#example').dataTable({
                "sPaginationType": "full_numbers",
                "bAutoWidth": true,
                "bServerSide": true,
                "iDisplayLength": 10,
                "deferLoading": ${totalCount?:0},
                "sAjaxSource": "${g.createLink(controller: 'androidGame',action: 'ajaxAndroidGameList')}",
                "fnRowCallback": function (nRow, aData, iDisplayIndex) {
                    if (aData.DT_RowId == undefined) {
                        return true;
                    }
                    $('td:eq(4)', nRow).html(getStatusIcon(nRow, aData[4])).css({textAlign: 'center'});
                    $('td:eq(5)', nRow).html(getStatusIcon(nRow, aData[5])).css({textAlign: 'center'});
                    $('td:eq(6)', nRow).html(getActionBtn(nRow, aData)).css({textAlign: 'center'});
                    return nRow;
                },
                "aoColumns": [
                    null,
                    { "bSortable": false },
                    { "bSortable": false },
                    { "bSortable": false },
                    { "bSortable": false },
                    { "bSortable": false },
                    { "bSortable": false }
                ]
            });

Answer:

In your DataTables initialization code you need to use option fnServerParams to modify data sent to the server.

I have also corrected deferLoading which should be iDeferLoading, see iDeferLoading.

Below is modified DataTables initalization code:

$('#example').dataTable({
    "sPaginationType": "full_numbers",
    "bAutoWidth": true,
    "bServerSide": true,
    "iDisplayLength": 10,
    "iDeferLoading": ${totalCount?:0},
    "sAjaxSource": "${g.createLink(controller: 'androidGame',action: 'ajaxAndroidGameList')}",
    "fnServerParams": function (aoData){
       aoData.push({ 
          "name": "wrapCheck", 
          "value": $("#wrapCheck").prop('checked') ? "1" : "" 
       });
    },
    "fnRowCallback": function (nRow, aData, iDisplayIndex) {
        if (aData.DT_RowId == undefined) {
            return true;
        }
        $('td:eq(4)', nRow).html(getStatusIcon(nRow, aData[4])).css({textAlign: 'center'});
        $('td:eq(5)', nRow).html(getStatusIcon(nRow, aData[5])).css({textAlign: 'center'});
        $('td:eq(6)', nRow).html(getActionBtn(nRow, aData)).css({textAlign: 'center'});
        return nRow;
    },
    "aoColumns": [
        null,
        { "bSortable": false },
        { "bSortable": false },
        { "bSortable": false },
        { "bSortable": false },
        { "bSortable": false },
        { "bSortable": false }
    ]
});

Then for checkbox click event handler all you need to do is:

DataTables 1.10

$('#wrapCheck').on('click', function (e) {
    $('#example').DataTable().ajax.reload();
});

DataTables 1.9

$('#wrapCheck').on('click', function (e) {
    $('#example').dataTable().fnDraw();
});

NOTE:

Please note, that your DataTables initialization code and server-side code are using older naming conventions for DataTables 1.9. DataTables 1.10 is backward compatible, meaning that it supports both new and old naming conventions. But with the release of new versions, the compatibility may be dropped, and you may want to consider updating your code according to 1.9 to 1.10 upgrade guide and Converting 1.9 naming to 1.10.


Related:


Stick tableinfo to specific place in jqueryDatable


jquery,css,datatables
everybody! I'm trying to stick tableInfo in jquery DataTable, like this But, when I chang value in show-list, the info slides down to the middle of column, like this I tried differnt variations of css to fix that, but I failed. now I use this code .dataTables_wrapper .dataTables_info { clear:...

How to conditionally display TableTools buttons


jquery,datatables,tabletools
I'm using jQuery DataTables and TableTools extension to display buttons in table header. But is there an option to show button when some condition is met? My table initialization code is shown below: projectsTable = $('#projects_table').DataTable({ "dom": '<"cleaner">lf<"cleaner">T<"cleaner"><"cleaner">rtip', "stateSave": true, "data":tableData, "bSortCellsTop": true, "responsive": true, "autoWidth": false, "tableTools":{ "aButtons": [...

How to dynamically add a row without “Requested unknown parameter” error


javascript,jquery,ajax,datatables
I am new to DataTables and I am having problems in dynamically adding a new row to the datatable. Here is my initialization: table = $("#college-list").DataTable({ 'ajax': { 'url': 'admin/get_college', 'type': 'GET' }, 'columns': [ { 'data': 'college_abbrev', "bSortable": true }, { 'data': 'college_name' , "bSortable": true }, { "mData":...

Datatable event on page change not working


jquery,datatables
This is what I want when the page is changed: $('#resultTable').on('page.dt', function() { if (document.getElementByID('r_tab').checked()) { $('.r_tab').show(); console.log('page changed on r'); } else { console.log('page changed on p'); $('.p_tab').show(); } }); When I run this code, I am not able to change the page anymore. Clicking on any page number/next...

grails 3.0.1 scaffolded view does not show domain relationship


grails,scaffolding
I am following the example in the book "Grails a Quick-Start Guide" using Grails 3.0.1 with following domains package com.tekdays class TekEvent { static constraints = { name() city() description maxSize:5000 organizer() venue() startDate() endDate() } String city String name TekUser organizer String venue Date startDate Date endDate String description...

Render a controller into a String


grails,grails-2.0
I can render a template or a view into a String, but how can I render a controller into a String ? I would like to perform this kind of operation: def myAction = { ... def html = renderToString(controller: 'myController', action: 'myAction', params: [what:'ever']) render modify(html) ... } ...

passing backbone collection to view


grails,backbone.js,handlebars
I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work. I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will...

Intercepting login calls with Spring-Security-Rest plugin in Grails


rest,grails,spring-security
I am using the spring security rest plugin for Grails to provide a login mechanism for an AngularJS app. Login works fine, but I can't figure out how to intercept login calls, in order to store additional statistics on (invalid/valid) login attempts. As I am quite new to Spring Security...

Grails logging auto inject


grails,logback
I use grails 3.0.2 and logback. How can I use this logger in my code, can I somehow autoinject it, like log.debug() in grails 2.x which was using org.apache.commons.logging.Log?

Grails: Carry forward params on g:actionSubmit is clicked


grails,gsp
How to carry forward the parameters when g:actionSubmit button is clicked? Here is my gsp code: <g:checkBox name="msgCheck" checked="" value="${userInstance.emailId}"></g:checkBox> ... <g:actionSubmit class="update" action="delete" value="Delete" params="${params}"></g:actionSubmit> Here is my controller code: def delete() { try { def user_list = params.msgCheck //deleting the user //successful. redirect(action: "list", params: params) } catch...

Grails 2.4.4 spring security role doesn't apply to user


java,spring,grails,spring-security,spring-annotations
I have controller: class AdminController { def springSecurityService @Secured(['ROLE_ADMIN', 'ROLE_USER']) def index() { render "test"; } And user with role ROLE_ADMIN in the table: But, when I use: springSecurityService.getPrincipal().getAuthorities() There is only one role: ROLE_NO_ROLES Why? def loggedInUser = springSecurityService.currentUser; returns correct user. Config: ... grails.plugin.springsecurity.userLookup.userDomainClassName = '...' grails.plugin.springsecurity.userLookup.authorityJoinClassName =...

Datatables Individual Column Search incompatible with scroll


jquery,css,datatables
I am using Datatables to display more than a thousand table rows. I use the individual column search to search specific columns. I initialize the table with: var table = $('#example').DataTable( { "scrollX": true, "scrollY": "400px", "paging": false }); However, when I search a column the second left column is...

Grails 2.3.9 - Error: ClassNotFoundException: grails.plugin.spock.test.GrailsSpecTestType


grails,grails-plugin,spock,grails-2.3
Whenever I enter the grails command: test-app I get this error: Error executing script TestApp: java.lang.ClassNotFoundException: grails.plugin.spock.test.GrailsSpecTestType (Use --stacktrace to see the full trace) In my BuildConfig.groovy I have: grails.project.dependency.resolution = { ... plugins { ... test ":spock:0.7" } } I've tried replacing it with compile ":spock:0.7" . I've also...

How to send current page number in Ajax request


javascript,jquery,ajax,spring-mvc,datatables
I am using jQuery DataTable to display huge amount of data in a table. I am getting data page wise on Ajax request like this: var pageNo = 1; $('#propertyTable').dataTable( { "processing": true, "serverSide": true, "ajax": "${contextPath}/admin/getNextPageData/"+pageNo+"/"+10, "columns": [ { "data": "propertyId" }, { "data": "propertyname" }, { "data": "propertyType"...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types


grails,groovy,jax-rs
While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

Server Side Pagination with jQuery Data Tables plugin


jquery,spring-mvc,datatables
How can I achieve server side pagination using data table? Currently, on load of page I am initializing the data table & filling the table with Data (JSON) coming from database via Java Spring controller. I am making an Ajax call by passing search criteria in query string. Since we...

ng-repeat sorting arrow not working in javascript datatables


javascript,jquery,angularjs,html5,datatables
I'm very new to AngularJs and datatables. I have a requirement to populate the data in table rows using ng-repeat. Iam able to populate the rows and enabling the sorting for the first time. When i click on the arrows to sort ascend or descend the row data wiping off....

Encryption of strings using AES 128 in Java/grails


java,grails,encryption,aes
I would like to encrypt 3 strings using AES 128 in Java / Grails, and using the code below, but i get the error "An error occurred when encrypting", can someone tell me what is wrong with my code, how to fix it. thanks in advance and to Stackoverflow. String...

Expand Child Rows of Responsive Datatables automatically


javascript,jquery,datatables,datatables-1.10
I have a responsive dataTable (Responsive doc.) in the following format: var dataTableInfo = j$('[id$="dataTableInfo"]').DataTable({ responsive: { "autoWidth": true, details: { type: 'column', target: 0 } }, columnDefs: [ { className: 'control', orderable: false, targets: 0 } ] }); I fill this with data through a search to an external...

jquery dataTables - creating a column with static content


jquery,datatables
I have the following logic to create a jquery dataTable: var selected = []; $('#users').DataTable( { "processing": false, "serverSide": true, "ordering": false, aLengthMenu: [ [10, 25, 50, 100, "-1"], [10, 25, 50, 100, "All"] ], "ajax": "/cgi-bin/pid_list", "rowCallback": function( row, data ) { if ( $.inArray(data.DT_RowId, selected) !== -1 )...

Warning: Requested unknown parameter '0' for row 0


javascript,datatables
I have the following code: var dummyData = { "activities": [ { "date": "19/06/2015 19:00", "user": "Dan", "display": "First Item" }, { "date": "19/06/2015 19:00", "user": "Andrew", "display": "Second Item" }, { "date": "19/06/2015 19:00", "user": "Trevor", "display": "Third Item" }, { "date": "19/06/2015 19:00", "user": "Bob", "display": "Fourth Item"...

jQuery DataTables with Node.js


javascript,jquery,node.js,datatables,jquery-datatables
So i am trying to implement a pagination table with the datatables plugin, this is my first time using this plugin. I followed the documentation on the plugin and tried to get the values from the server through the use of Ajax, as per presented in the plugins documentation. I...

Render currency and symbol and combine with data from a different cell


javascript,jquery,datatables
I am working with latest jQuery DataTables v1.10.7 and I am trying to parse a number into the following format: $239.90 USD I am being able make the currency working with this command: columns: [ { data: "Price", render: $.fn.dataTable.render.number(',', '.', 2, '$') }, however the output of this is...

Edit and Delete on mouseover of jQuery Datatable


jquery,css3,datatables,jquery-datatables-editor
I am trying to show edit and delete buttons on mouse over of a tr in jQuery Datatable. In the process, I am almost done, but I have defined 3rd column to contain edit and delete buttons. Below is the html and jQuery code <table id="example" class="display" cellspacing="0" width="100%"> <thead>...

Datatable.js make table from object


javascript,jquery,datatables,jquery-datatables
Suppose I have a set of objects that each contain data I want to store into a data table. Per the documentation, I would normally do something like: var dataSet = [ ['Trident', 'Internet Explorer 4.0', 'Win 95+', '4', 'X'], ['Trident', 'Internet Explorer 5.0', 'Win 95+', '5', 'C'], ['Trident', 'Internet...

Log Grails Pre 3.0 startup time


grails
In Grails 2.x.x is it somehow possible to log the startup time? We are currently trying to optimize the application startup and having the startup time logged would help tremendously.

jQuery dataTables - Remove an HTML element from a cell


jquery,datatables
Trying to dynamically edit cells based on different JQuery events. This is what I'm hoping that should be done to the data (putting together the fns in simpler way) var d = table.cell(rowindex,cellindex).node().remove(".custom-class1"); table.cell(rowindex,cellindex).data(d); Example data on cell, <td> <span class="custom-class1"></span> <span class="custom-class2"></span> </td> The cell data should be replaced...

alert grails pagination current offset value


grails,pagination
I am using Grails 2.4.2. I have a list which is using pagination. When I mouse hover a number or next page icon it shows current offset number as tool tip. Can I alert this offset number or get my list's current page offset number?

How to make custom date sort in datatables?


javascript,jquery,datatables
I have table with column of dates: 2015-03-03 20:14 2015-04-15 20:33 2015-04-20 09:34 2015-04-28 22:18 But some cells have no date (I mark it -). When I am using the general sorting function it looks like: — — — 2015-03-03 20:14 2015-04-15 20:33 2015-04-20 09:34 2015-04-28 22:18 but I need:...

How to search and filter which table columns are displayed


jquery,jquery-ui,datatables
I have a data table that has 100+ columns: California - Los Angeles California - SF Illinois - Chicago Texas - Austin Texas - Houston ..... etc How can I create a search input field that allows me to filter which columns are being shown? I'm thinking something similar to...

Decode base64 image in Grails [duplicate]


grails,groovy
This question already has an answer here: Convert base64 string to image 3 answers I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string { "imageData":"base64encoded string", "status":"1" } where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp I cant post...

Groovy - timestamp from minutes


oracle,grails,groovy,timestamp
I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

DataTables plug-in - Display scrollbar below tfoot tag?


javascript,datatables,jquery-datatables
I use jQuery DataTables plug-in and "scrollX":true for horizontal scrolling. Why scroll bar appears above tfoot tag? How to make it appear below footer? var table = $('#example') .DataTable( { "scrollX": true, "scrollCollapse": true, "dom": 'Zlrtip', "colResize": { "tableWidthFixed": false, //"handleWidth": 10, "resizeCallback": function(column) { } }, "searching": false, "paging":...

[B cannot be cast to java.sql.Blob


grails,gorm
This is my domain class class TimesheetSubmission { Date submissionDate=new Date() String foreman String shift String jobId Date date byte[] xmlSubmission String xmlResponse static constraints = { submissionDate nullable: false foreman nullable: false shift nullable: false jobId nullable: false date nullable: false xmlSubmission nullable: true xmlResponse nullable: false } static...

DataTables Warning: Requested unknown parameter 'pCodigo' for row 0


asp.net-web-api,datatables
I'm trying to populate a table on a button click, getting the data from an ASP.NET ApiController. I've tried with almost all solutions posted in SO to other similar issues but always get that error. Hope someone sees the problem. The html markup: <input type="button" ID="btnSearch" name="btnSearch" class="btn btn-success" value="Buscar"...

Grails 3.0 Searchable plugin


maven,grails
I've tried to use the searchable plugin in grails 3.0, but I am not sure wheather it is compatible or not. I've added compile "org.grails.plugins:searchable" to the dependencies. The build completes but yields a NotSearializableException: > Configuring > 1/1 projects > Resolving dependencies ':agent' > Resolving dependencies ': BUILD SUCCESSFUL...

Intellij IDEA long processing for grails app with warning “too much output to process”


grails,intellij-idea,jvm
I new to Intellij for Grails app while run the app it execute lot of thing with the warning "Too much output to process" & takes comparatively more time to start the server. Below is the log screen (AbstractAutowireCapableBeanFactory.java:539) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) at...

Convert a column of text URLs into active hyperlinks in Shiny


r,url,hyperlink,datatables,shiny
I am creating a user interface for a pathway enrichment program. The results are shown in a table as shown below. Below is a snippet showing that I am using DT::renderDataTable and DT::datatable to output the table in a tab. spia_out() is just a reactive function that runs the pathway...

Error when using angular with Grails


angularjs,grails
Here is my index.gsp <!DOCTYPE html> <html ng-app="myApp"> <head> <title>my app</title> </head> <body> <input type="text" data-ng-model="test"/> {{test}} </body> <script src="/js/angular.min.js"></script> </html> When I build an app, There is an error like this, Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=myApp&p1=Error%3A%…20at%20d%20(http%3A%2F%2Flocalhost%3A8000%2Fjs%2Fangular.min.js%3A17%3A381)...

unable to resolve class org.apache.commons.net.ftp in grails


grails,apache-commons
I am developing a module in which some file need to be uploaded on a ftp server for that I have added the "commons-net-3.3.jar" in my grails app & while using it import org.apache.commons.net.ftp.FTP import org.apache.commons.net.ftp.FTPClient import org.apache.commons.net.ftp.FTPClientConfig import org.apache.commons.net.ftp.FTPFile import org.apache.commons.net.ftp.FTPReply It is throwing the error unable to resolve...

datatables.js is munging the rendered output


javascript,datatables
I have the wierdest thing happening. I have the following code segment: $('#workQueueTable').DataTable({ "data": requests, "columns": [ { "title": "Project ID", "data":"ProjectID", "render": function(data) { return '<a href="javascript:void();" onclick="getDataFromSP("FormByID", "' + data + '")"' + '>' + data + '</a>'; } }, { "title": "Project Description", "data": "Title", "sWidth": "50%"...

Execute controller function in Grails via Ajax


javascript,jquery,ajax,grails,gsp
I am a novice with ajax in Grails. I want to try to execute a controller method from gsp-code from ajax. This is part of my gsp-code: <g:select optionKey="id" name="region.id" id="region" from="${region}" noSelection="[null:' ']" onchange="categoryChanged(this.value);" ></g:select> <div> <b>Sub-Category: </b> <span id="subContainer"></span> </div> <script> function categoryChanged(regionId) { $.ajax({type:'POST',data:'regionId='+regionId,...

Grails: Do addTo* and removeFrom* require a call to save?


grails,gorm,grails-2.0,grails-domain-class
In the docs some examples have a call to save whereas some others do not. I'm assuming that addTo* needs the call to save whereas removeFrom* doesn't. Am I mistaken?

grails one to many with additional column


grails,relationship,one-to-many
In my Grails project I need to have a 1:N relationship between two domain classes. So, I've created the following domain class: class Receipt_HealthService { Receipt receipt HealthService healthService int quantity = 1 static constraints = { } } and in Receipt I have the following: @NotNull static hasMany =...

Find and replace cells value with Datatables plugin


javascript,jquery,datatables
i'm looking to find and replace specific values from a known column with the plugin called Datatables. Here is my code to do that : table.columns(5).search('valuetochange').cells().every( function () { this.data('newvalue'); }); But it is not working, I also tried other solutions but I didn't find a way to update the...

How to declare javascript asset in the view to be rendered within the footer using Grails Asset Pipeline


grails,grails-plugin
Since there is no deferred option for: <asset:javascript src="custom_view_script.js"/> What else can be used, outside of resource plugin, to place view specific script right before the closing body tag and without declaring it globally in layout? I do know about: <asset:deferredScripts/> but that only handles on page script and not...

File upload with grails and jquery


jquery,grails
I have a form with multiple inputs plus a doc or pdf file upload. //Multiple input fields are here then upload -> <div class="controls"> <div class="fileupload ${ person?.attachment ? 'fileupload-exists' : 'fileupload-new' }" id="attachment" data-provides="fileupload" data-name="attachment"> <span class="btn btn-file"> <span class="fileupload-new">Add</span> <span class="fileupload-exists">Change</span> <input type="file" /> </span> <span class="fileupload-preview"></span>...

grails DataSource.groovy refer bean for decoding password


grails
Referring https://jira.grails.org/browse/GRAILS-3620, we need to specify a class with static methods to decode the encrypted password in DataSource config. For passwordEncryptionCodec property, is it possible to refer to a bean defined in resources.xml or any other grails bean definition files? For ex: having a decrypted Properties bean in resoures.xml or...

Grails 3.0.2 missing generate-views


java,grails,command-line,ide,ggts
I'm new to grails and I'm trying to get my first HelloWorld from it. I can generate it with the controller, but I can't create a view because it isn't listed in the Grails (3.0.2) list of command. Because any IDE support grails 3.*, I can't create it by that...

Use data-* attribute in grails g.link generated in tagLib


grails
Is there a way to use data- attributes in g.link generated by a tagLib? I want to store some DOM info instead of using params in the g.link which results in query parameters. Example: out << g.link(controller: "calendar", action: "info", params: [id: cal_id], data-info: "abc") { "click me " }...