Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Problem

I'm using server side pagination and search, pagination is working fine but when i enter some text into search box which automatically sends request to server, it immediately returns back with empty object but its also bringing "recordsTotal" for pagination to work. which means one query is executing but the second one is NOT.

API Test using postman

I've tested the API USING POSTMAN and what ever search string i send, it brings me back the appropriate results but when i send it via search box (FROM FRONT END) it just simply won't work

enter image description here

Here is my Controller Code:

I've intentionally commented "fnCallback(records)" but I'm consoling "console.log(result)" the result array returned from back-end API

angular.module('withServerSide', ['datatables'])
.controller('withServerSideController', function WithPromiseController($scope, DTOptionsBuilder, DTColumnBuilder, filterService)
{
    $scope.dtColumns = [
        DTColumnBuilder.newColumn('es_officer_id', 'Id').withOption('searchable', true),
        DTColumnBuilder.newColumn('es_officer_name', 'Name').withOption('searchable', true)
    ];

    $scope.dtOptions = DTOptionsBuilder
        .newOptions()
        .withFnServerData(serverData)
        .withDataProp('data') // tried data aswell
        .withOption('processing', true)
        .withOption('serverSide', true)
        .withOption('paging', true)
        .withOption('stateSave', true)
        .withOption('lengthMenu', [5, 10, 20, 30, 50, 100 ])
        .withDisplayLength(5)
        .withPaginationType('full_numbers')
        .withButtons([
            'colvis',
            'print',
            'excel'
        ])

    function serverData(sSource, aoData, fnCallback, oSettings) 
    {
        //All the parameters you need is in the aoData variable

        var draw   = aoData[0].value;             
        var limit  = aoData[4].value;               // item per page
        var order  = aoData[2].value[0].dir;    // order by asc or desc
        var start  = aoData[3].value;              // start from
        var search = aoData[5].value;           // search string

        //Then just call your service to get the records from server side
        filterService.execute(start, limit, order, search).then(function(result)
        {    
            console.log(result);

            // var records = {
            //         'draw': draw,
            //         'recordsTotal': result.data.recordsTotal,
            //         'recordsFiltered': result.data.recordsFiltered,
            //         'data': result.data.es_officers  
            //     };

            // // console.log(records);

            // fnCallback(records);
        });
    }
});

Here is Code for filterService factory:

angular.module('Main_Module').factory('filterService', filterService);
filterService.$inject = ['$q', '$http']
function filterService($q, $http)
{
    var service = {
    execute: execute
    };

    return service;

        //               Start-From  LIMIT   ASC | DESC
        function execute(start, limit, order, search)
        {
            // console.log(start, length, order);

            var defered = $q.defer();
            //Make a request to backend api and then call defered.resolve(result);

            // /SELECTSpecific/:TableName/:Start/:Length/:Order
            $http({ 
                url   : 'http://localhost:3000/api/SELECTQPromise/es_officers/'+start+'/'+limit+'/'+order+'/'+search,
                method: 'POST'
            })
            .then(function(result) 
            {                      
                defered.resolve(result);
            })
            .catch(function(err)
            {
                defered.reject(err);
            });


            return defered.promise;
        }
};

Back-end Code:

router.post('/SELECTQPromise/:TableName/:start/:limit/:order/:search', function(req, res)
{

    function doQuery1()
    {
        var query1 = "SELECT COUNT(*) AS recordsTotal FROM " + req.params.TableName;

        var defered = Q.defer();
        connection.query(query1, function(err, result) //defered.makeNodeResolver()
        {
            if(err)
            {
                defered.reject(err);
            }
            else
            {
                defered.resolve(result[0]);
            }
        });

        return defered.promise;
    }


    function doQuery3()
    {
        var query3 = "SELECT es_officer_id, es_officer_name FROM "+req.params.TableName+
                     " WHERE es_officer_name LIKE '%"+req.params.search+"%'"+
                     " ORDER BY es_officer_id "+req.params.order;//+" LIMIT "+req.params.start+", "+req.params.limit;

        var defered = Q.defer();
        connection.query(query3, function(err, result) //defered.makeNodeResolver());
        {
            if(err)
            {
                defered.reject(err);
            }
            else
            {
                defered.resolve(result);
            }
        });

        return defered.promise;
    }


    Q.all([doQuery1(), doQuery3()]).then(function(result)
    {
        // res.json({"Error" : false, "Message" : "success", [req.params.TableName] : result[1], "recordsTotal": result[0].recordsTotal, "recordsFiltered": result[0].recordsTotal});  
        res.send(result);
    })
    .catch(function(err)
    {
        res.send(err);
    });
});
share|improve this question
    
Unrelated but anything where I see incoming request parameter just appended to a SQL-query gives me chills down my spine. Are you 100% sure your code is not open to SQL-injections? – ippi Jun 13 at 14:22
    
I know it is open to SQL injection, I intentionally replaced "?" with direct parameter variables, I will fix that once it starts working I will replace the stuff with "?" but this is driving me nuts why am i receiving result for one query and not for the other one. – Wcan Jun 13 at 15:01

I've figured out the problem and I'm mentioned it here in case if anyone face the same problem in the future.

on this line I thought I'm assigning value to search where as in actual .value itself.

var search = aoData[5].value;

the search string is with the .value object, the correct would be

var search = aoData[5].value.value;

Now its working absolutely fine.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.