Pagination draw value wrong change when i click on paginate

Pagination draw value wrong change when i click on paginate

MoazzamAliMoazzamAli Posts: 6Questions: 1Answers: 0
edited July 15 in Free community support

Link to test case:

    var objDatatables = null;
    require(["jquery","mage/url","datatables"], function($,urlBuilder,datatables){
        objDatatables = datatables;
        var savedPage = localStorage.getItem('savedPage') ? parseInt(localStorage.getItem('savedPage')) : 0;
        var table = new objDatatables('#example',{
            "processing": true,
            "serverSide": true,
            "paging": true,
            stateSave: false,
            "ajax": {
                "url": '<?= $block->getUrl('pricecalculator/main/pricecalculation') ?>',
                "data": function ( d ) {
                    var searchValue = $('#dt-search-0').val();
                    if (!searchValue) {
                        return false; // Stop the request if search value is empty
                    }
                    return $.extend( {}, d, {
                        "new_draw": "value2"
                    });
                }
                // "dataSrc": ""
            },
            "columns": [
                { "data": "sku" },
                { "data": "name" },
                { "data": "magento_cost" },
                { "data": "match_data" }
            ],
            "initComplete": function(settings, json) {
                // Perform a search on a specific column after data has loaded
                $('#dt-search-0').unbind();
                $('#dt-search-0').on('keyup', function(e) {
                    if(e.keyCode === 13) {
                        table.search( $('#dt-search-0').val()).draw();
                        table.columns(0).search($('#dt-search-0').val()).draw(); // Search for the value in the 'Position' column (index 1)
                        table.columns(1).search($('#dt-search-0').val()).draw(); // Search for the value in the 'Position' column (index 1)
                        table.columns(2).search($('#dt-search-0').val()).draw(); // Search for the value in the 'Position' column (index 1)
                    }
                });
            },
        });
    });

Debugger code (debug.datatables.net):

https://www.awesomescreenshot.com/image/49386962?key=ceb32dc8ff55883d3f39fcdae96fbd81
Error messages shown:
Description of problem:

Answers

  • allanallan Posts: 63,356Questions: 1Answers: 10,444 Site admin

    Pagination draw value wrong change when i click on paginate

    The screenshot shows the response from the server. If that is wrong, then, the problem is in the server-side processing script.

    It should be the same as whatever was submitted as the draw value (cast as an integer for security).

    If that isn't happening for you, I'd need a link to a test case and to see the PHP code in question.

    Allan

  • MoazzamAliMoazzamAli Posts: 6Questions: 1Answers: 0
    edited July 15

    ** Here is php code
    basically draw get from datatables and datatables transfer the draw param to server
    side script so draw is getting wrong from datatables**

            $request = $this->getRequest()->getParams();
            $paginateNumber = $request['draw'];
            $size = $request['length'];
            $orderBy = $request['order'][0]['dir'];
            $searchValue = $request['search']['value'] ?? $this->getRequest()->getParam('columns')[0]['search']['value'];
            $productCollection = '';
            if (!empty($searchValue)) {
                $productCollection = $this->filterSearchData($searchValue, $request);
            } else {
                $productCollection = $this->productCollectionFactory->create();
                $productCollection->addAttributeToSelect('name');
                $productCollection->addAttributeToSelect('price');
                $productCollection->addAttributeToSelect('special_price');
                $productCollection->addAttributeToSelect('sku');
                $productCollection->addAttributeToSelect('entity_id');
                $productCollection->addAttributeToSelect('type_id',  ['eq' => 'simple']);
                $productCollection->setOrder('entity_id', $orderBy);
                $productCollection->setCurPage($paginateNumber)->setPageSize($size)->load();
            }
            $data = [];
            $i = 0;
            foreach ($productCollection->getItems() as $product) {
                $data[$i]['sku'] = $product->getData('sku');
                $data[$i]['name'] = $product->getData('name');
                $data[$i]['magento_cost'] = $this->priceHelper->currencyByStore($product->getData('price'), 1);
                $data[$i]['match_data'] = 'No Match';
                $i++;
            }
            $response = [
                'draw' => intval($paginateNumber),
                'recordsTotal' => $productCollection->getSize(),
                'recordsFiltered' => $productCollection->getSize(),
                'data' => $data
            ];
            $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            return $result->setData($response);
        }
    
        public function filterSearchData($searchValue, $request)
        {
            $paginateNumber = $request['draw'];
            $size = $request['length'];
    //        $pageNumber = $request['length'];
            $orderBy = $request['order'][0]['dir'];
            $searchValue = $request['search']['value'];
            $productCollection = $this->productCollectionFactory->create();
            $productCollection->addAttributeToSelect('name');
            $productCollection->addAttributeToSelect('price');
            $productCollection->addAttributeToSelect('special_price');
            $productCollection->addAttributeToSelect('sku');
            $productCollection->addAttributeToSelect('entity_id');
            $productCollection->addAttributeToSelect('type_id',  ['eq' => 'simple']);
            if($searchValue) {
                $column0 = $this->getRequest()->getParam('columns')[0]['data'];
                $searchValueSku = trim($this->getRequest()->getParam('columns')[0]['search']['value']);
                if (str_contains($searchValueSku, '€')){
                    $searchValueSku = str_replace('€','', $searchValueSku);
                }
                if ($column0 == 'sku') {
                    $productCollection->addAttributeToFilter(
                        [
                            [
                                'attribute'=>'sku',
                                'like'=> '%'.$searchValueSku.'%'
                            ],
                            [
                                'attribute'=>'name',
                                'like'=> '%'.$searchValueSku.'%'
                            ],
                            [
                                'attribute'=>'price',
                                'like'=> '%'.$searchValueSku.'%'
                            ]
                        ]
                    );
                    $productCollection->setOrder('entity_id', $orderBy);
                    $productCollection->setCurPage($paginateNumber)->setPageSize($size)->load();
                    if ($productCollection->count()) {
                        return $productCollection;
                    }
                }
            }
        }
    

    Edited by allan to add syntax highlighting - see docs here.

  • MoazzamAliMoazzamAli Posts: 6Questions: 1Answers: 0
    edited July 15

    Here is my php code
    i am giving the int value in draw param

    $request = $this->getRequest()->getParams();
            $paginateNumber = $request['draw'];
            $size = $request['length'];
            $orderBy = $request['order'][0]['dir'];
            $searchValue = $request['search']['value'] ?? $this->getRequest()->getParam('columns')[0]['search']['value'];
            $productCollection = '';
            if (!empty($searchValue)) {
                $productCollection = $this->filterSearchData($searchValue, $request);
            } else {
                $productCollection = $this->productCollectionFactory->create();
                $productCollection->addAttributeToSelect('name');
                $productCollection->addAttributeToSelect('price');
                $productCollection->addAttributeToSelect('special_price');
                $productCollection->addAttributeToSelect('sku');
                $productCollection->addAttributeToSelect('entity_id');
                $productCollection->addAttributeToSelect('type_id',  ['eq' => 'simple']);
                $productCollection->setOrder('entity_id', $orderBy);
                $productCollection->setCurPage($paginateNumber)->setPageSize($size)->load();
            }
            $data = [];
            $i = 0;
            foreach ($productCollection->getItems() as $product) {
                $data[$i]['sku'] = $product->getData('sku');
                $data[$i]['name'] = $product->getData('name');
                $data[$i]['magento_cost'] = $this->priceHelper->currencyByStore($product->getData('price'), 1);
                $data[$i]['match_data'] = 'No Match';
                $i++;
            }
            $response = [
                'draw' => intval($paginateNumber),
                'recordsTotal' => $productCollection->getSize(),
                'recordsFiltered' => $productCollection->getSize(),
                'data' => $data
            ];
            $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            return $result->setData($response);
        }
    
        public function filterSearchData($searchValue, $request)
        {
            $paginateNumber = $request['draw'];
            $size = $request['length'];
    //        $pageNumber = $request['length'];
            $orderBy = $request['order'][0]['dir'];
            $searchValue = $request['search']['value'];
            $productCollection = $this->productCollectionFactory->create();
            $productCollection->addAttributeToSelect('name');
            $productCollection->addAttributeToSelect('price');
            $productCollection->addAttributeToSelect('special_price');
            $productCollection->addAttributeToSelect('sku');
            $productCollection->addAttributeToSelect('entity_id');
            $productCollection->addAttributeToSelect('type_id',  ['eq' => 'simple']);
            if($searchValue) {
                $column0 = $this->getRequest()->getParam('columns')[0]['data'];
                $searchValueSku = trim($this->getRequest()->getParam('columns')[0]['search']['value']);
                if (str_contains($searchValueSku, '€')){
                    $searchValueSku = str_replace('€','', $searchValueSku);
                }
                if ($column0 == 'sku') {
                    $productCollection->addAttributeToFilter(
                        [
                            [
                                'attribute'=>'sku',
                                'like'=> '%'.$searchValueSku.'%'
                            ],
                            [
                                'attribute'=>'name',
                                'like'=> '%'.$searchValueSku.'%'
                            ],
                            [
                                'attribute'=>'price',
                                'like'=> '%'.$searchValueSku.'%'
                            ]
                        ]
                    );
                    $productCollection->setOrder('entity_id', $orderBy);
                    $productCollection->setCurPage($paginateNumber)->setPageSize($size)->load();
                    if ($productCollection->count()) {
                        return $productCollection;
                    }
                }
            }
        }
    

    Edited by allan to add syntax highlighting - see docs here.

  • allanallan Posts: 63,356Questions: 1Answers: 10,444 Site admin

    That looks okay. That should mean if the client-side sends 4 for the draw, then the server-side will reply with a 4.

    No link to a test case has been provided, so I can't see if that is what is happening, but that looks like what should be happening, and is what is required.

    Allan

  • MoazzamAliMoazzamAli Posts: 6Questions: 1Answers: 0

    Thanks, Allen of your response but datables

    1:- When I click on 2 pagination it works fine .

    2:- then I click again on 1 pagination then it should get the draw value 1 but it is getting the 3 value that is major issue during pagination wrong draw value

  • MoazzamAliMoazzamAli Posts: 6Questions: 1Answers: 0
    edited July 15

    Hi @allan ,
    how can I keep the pagination after reload the page can you help me

    Thanks

  • kthorngrenkthorngren Posts: 21,260Questions: 26Answers: 4,932

    2:- then I click again on 1 pagination then it should get the draw value 1 but it is getting the 3 value that is major issue during pagination wrong draw value

    No the draw parameter is a sequence number not the page number. It will increment by one for each request to the server. See the server side processing protocol docs for details.

    Read about the start and length parameters. They are used to provide the server script information about the data for the page displayed.

    Kevin

  • MoazzamAliMoazzamAli Posts: 6Questions: 1Answers: 0
    edited July 15

    Hi @kthorngren
    How we can update the parameter in data tables,

    like draw value, length etc

  • kthorngrenkthorngren Posts: 21,260Questions: 26Answers: 4,932
    edited July 15

    How we can update the parameter in data tables,

    I don't understand what you want to update. Please be more specific. Maybe you can provide more specific details of the problem you are trying to resolve. There are no details of what you expect different in the screenshot. It looks like you clicked page 1 and that is what the JSON response contains.

    If you want to change the sent parameters then use the preXhr event. If you need to convert the returned parameters to what Datatables supports then use the xhr event.

    Kevin

  • kthorngrenkthorngren Posts: 21,260Questions: 26Answers: 4,932
    edited July 15

    I'm not familiar with setCurPage() but possibly what you need to do is calculate the value sent to setCurPage($paginateNumber). Instead of this:

    $paginateNumber = $request['draw'];
    

    This might work:

    $paginateNumber = $request['start'] / $request['length'];
    

    Kevin

Sign In or Register to comment.