Skip to content
This repository was archived by the owner on Feb 2, 2025. It is now read-only.

Angular datatables ajax pagination using nodejs and mongodb #710

Closed
shahzadthathal opened this issue Apr 30, 2016 · 22 comments
Closed

Angular datatables ajax pagination using nodejs and mongodb #710

shahzadthathal opened this issue Apr 30, 2016 · 22 comments
Labels

Comments

@shahzadthathal
Copy link

shahzadthathal commented Apr 30, 2016

I'm trying to implement server side pagination in angular datatables but unfortunately I'm completely failed, can some one pls have a look into my code. No product showing in table, how I can initially fill $scope.products array? How I can then use ajax pagination? how I can pass page no, limit? Also pls look into server side function too. Any help would be highly appreciated!

ProductCtrl:

adminApp.controller('CrudCtrl', ['$scope','$compile', 'DTOptionsBuilder', 'DTColumnBuilder', function($scope, $compile, DTOptionsBuilder, DTColumnBuilder ){

$scope.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('ajax', {
         // Either you specify the AjaxDataProp here
        // dataSrc: 'data',
         url: '/api/product/list',
         type: 'GET'
     })
     // or here
        .withDataProp('data')
        .withOption('aLengthMenu', [5, 10, 20, 50, 100,500])
        .withOption('processing', true)
        .withOption('serverSide', true)
        .withPaginationType('full_numbers')
        .withOption('createdRow', function(row, data, dataIndex) {
              $compile(angular.element(row).contents())($scope);
       })
    $scope.dtColumns = [
        DTColumnBuilder.newColumn('_id').withTitle('ID').notVisible(),
        DTColumnBuilder.newColumn('title').withTitle('Title'),
        DTColumnBuilder.newColumn('description').withTitle('Description'),
        DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable()
            .renderWith(function(data, type, full, meta) {
                return '<button class="btn btn-warning" ng-click="showModal(' +  data  + ')">' +
                    '   <i class="fa fa-edit"></i>' +
                    '</button>&nbsp;' +
                    '<button class="btn btn-danger" ng-click="deleteItem(' + data+ ')">' +
                    '   <i class="fa fa-trash-o"></i>' +
                    '</button>';
            })
    ];

    $scope.showModal = function (product = null) {
        console.log(product);
    }

    $scope.deleteItem = function(model){
        console.log(product);
    }
}]);    

Product.html

<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-striped table-bordered table-hover">
    </table>

Product Data from server

{"recordsTotal":23,"recordsFiltered":23,"draw":"1","data":[{"_id":"57262c0a09be8dd4bef212a2","title"
:"Product 1","sale_price":77,"description":"Product description.","__v":0},{"_id":"57262d3609be8dd4bef212a3"
,"title":"Product 2","sale_price":88,"description":"Product 2 description","__v":0},{"_id":"5726310409be8dd4bef212a4"
,"title":"Product 3","sale_price":58,"description":"pppsd","__v":0},{"_id":"57264d2809be8dd4bef212a5"
,"title":"Product 5","sale_price":99,"description":"Product 5","__v":0},{"_id":"57264d3b09be8dd4bef212a6"
,"title":"Product 6","sale_price":888,"description":"Product 6","__v":0}]}

I wan to pass object to showModel() function but getting this erorr:

Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 19 of the expression [showModal([object Object])] starting at [Object])].
http://errors.angularjs.org/1.5.5/$parse/syntax?p0=Object&p1=is%20unexpected%2C%20expecting%20%5B%5D%5D&p2=19&p3=showModal(%5Bobject%20Object%5D)&p4=Object%5D)
@shahzadthathal
Copy link
Author

I'm getting this error:

Error: e[i] is undefined

@l-lin
Copy link
Owner

l-lin commented May 2, 2016

Several points:

  • you are using the server side processing, so you do not need the ngRepeat in your HTML
  • the recordsTotal is the total number of records, not the number of records you are displaying, same for recordsFiltered
  • the issue must come from your ajax.data function

@l-lin l-lin added the question label May 2, 2016
@shahzadthathal
Copy link
Author

I have updated my question, pls see.
I want to pass complete object to function showModal()
I'm getting this error:

Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 19 of the expression [showModal([object Object])] starting at [Object])].
http://errors.angularjs.org/1.5.5/$parse/syntax?p0=Object&p1=is%20unexpected%2C%20expecting%20%5B%5D%5D&p2=19&p3=showModal(%5Bobject%20Object%5D)&p4=Object%5D)

@l-lin
Copy link
Owner

l-lin commented May 2, 2016

In the renderWith function, data is an object. Unfortunately, you can only put string or integer because it's rendered by datatables. See #299.

@shahzadthathal
Copy link
Author

Then How I can pass a string into showModel() like: 570546d96d4f67e0123bb724?

@shahzadthathal
Copy link
Author

When I used this method:

DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable()
            .renderWith(function(data, type, full, meta) {
                return '<button class="btn btn-warning" ng-click="showModal(' +  data._id  + ')">' +
                    '   <i class="fa fa-edit"></i>' +
                    '</button>&nbsp;' +
                    '<button class="btn btn-danger" ng-click="deleteItem(' + data._id + ')">' +
                    '   <i class="fa fa-trash-o"></i>' +
                    '</button>';
            })

Getting this error:

Error: [$parse:syntax] Syntax Error: Token 'd96d4f67e0123bb724' is unexpected, expecting [)] at column 17 of the expression [showModal(570546d96d4f67e0123bb724)] starting at [d96d4f67e0123bb724)].
http://errors.angularjs.org/1.5.3/$parse/syntax?p0=d96d4f67e0123bb724&p1=is%20unexpected%2C%20expecting%20%5B)%5D&p2=17&p3=showModal(570546d96d4f67e0123bb724)&p4=d96d4f67e0123bb724)

@l-lin
Copy link
Owner

l-lin commented May 2, 2016

It's a string, so you need add quotes:

.renderWith(function(data, type, full, meta) {
                return '<button class="btn btn-warning" ng-click="showModal(\'' +  data._id  + '\')">' +
                    '   <i class="fa fa-edit"></i>' +
                    '</button>&nbsp;' +
                    '<button class="btn btn-danger" ng-click="deleteItem(\'' + data._id + '\')">' +
                    '   <i class="fa fa-trash-o"></i>' +
                    '</button>';
            })

@shahzadthathal
Copy link
Author

Thank for your help, I want to show image in table, is it possible?

@shahzadthathal
Copy link
Author

Okay I got the solution:

DTColumnBuilder.newColumn(null).withTitle('Image').renderWith(function(data, type, full, meta) {
            return '<img ng-src="'+ $scope.imageUrl+ data.image+'" height="70" width="80" alt=""/>';
        }),

@shahzadthathal
Copy link
Author

shahzadthathal commented May 3, 2016

Search issue.
When I type into search box it do not search, how I can fix it?
which parameter send to server when I type in search box?

@kevintc
Copy link

kevintc commented May 4, 2016

You can trigger a search by using :
dtInstance.DataTable.columns(id).search(text).draw();
where id is the column index and text is a string

You can then monitor the ajax request that is made to the server. Check the following documentation : https://datatables.net/manual/server-side
On the server side, you will have to parse the request and then send back the results.

@shahzadthathal
Copy link
Author

Okay let me try

@shahzadthathal
Copy link
Author

Hi,

I'm using now on button click searching feature and I see in request search value is atached this way: search[value] = abc,
How I can get this value on server side?

.withOption('initComplete', function() {
             $('.dataTables_filter input').unbind();
             $('<button/>').addClass('btn btn-info btn-sm').text('search').attr('id', 'new-search').appendTo('.dataTables_filter');
             $('#new-search').on('click', function() { 
               $scope.dtInstance.DataTable.search($('.dataTables_filter input').val()).draw();
             })  
         })

@kevintc
Copy link

kevintc commented May 10, 2016

Check the navigator network monitor tab (use development tools from Chrome or Firefox).
Do you see the requests being made when you trigger the search ?

Check the parameters from the POST request, you will see a JSON object, this is the one you will get on server side. To retrieve it, depending on the language you use, will be as simple as retrieving a POST object and then parse it from json to a dictionnary.

Using python with Flask and the request module, I can then write :

table_params = byteify(request.json)
print table_params['search']['value']
...

For php, it would be :

if (isset($_POST['draw'])) { $draw = $_POST['draw']; }
if (isset($_POST['search'])) { $search = intval($_POST['search']); }
...

Take a look at the documentation for a full list of the variables you can use. You can even send your own custom variables from the client-side and catch them on the server-side.

@shahzadthathal
Copy link
Author

shahzadthathal commented May 10, 2016

Hi,
I'm getting value when I clicked on Search button: req.query.search.value

But the issue is my mongodb not search this value, here is my function;

function list(req) {
    var list = {};
    var searchString;

      if(req.query.search.value)
        searchString = '{product_name:/'+req.query.search.value+'/}';
      else
        searchString = '{}';

    console.log(searchString);

    return Models.SaleModel.count()
         .then(function(total){
          list.recordsTotal = total;
          list.recordsFiltered = total;
          return Models.SaleModel.find(searchString).skip(req.query.start).limit(req.query.length).sort({_id:-1});
         })
         .then(function(results){

           list.draw = req.query.draw;
           list.data = results;
           return list;
         });
}

@kevintc
Copy link

kevintc commented May 11, 2016

This is your client side function, you need to check your server side. It sees the search value, so you need to check your query.
Do you get any response when you try to query it ? or is 'results' empty ?

@shahzadthathal
Copy link
Author

No this is my Server side function and I get [] this response.
I think my query is not working as I expect.

@kevintc
Copy link

kevintc commented May 13, 2016

Cannot help you without further details (specially your find function)

@shahzadthathal
Copy link
Author

Hi,
Can you pls post here a example, how can I find using Nodejs?

@kevintc
Copy link

kevintc commented May 14, 2016

I don't know enough about NodeJS to be of any help, you can check the documentation https://docs.mongodb.com/getting-started/node/query/ and check your Models.SaleModel.find() function.

@vinicius0026
Copy link

@shahzadthathal take a look at https://github.com/fiddus/datatables-query, a module that I wrote to perform server-side rendering for datatables, using Node.js (w/ express) and MongoDB (w/ mongoose) on the server.

@shahzadthathal
Copy link
Author

Hi

I will give it a try.

Thanks

@l-lin l-lin closed this as completed Nov 28, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

4 participants