When I resize the page , start new query...why?

When I resize the page , start new query...why?

Maxilboss93Maxilboss93 Posts: 33Questions: 6Answers: 0

hi promgrmmers, I have a problem with datatable, when i resize the dimension of the page , for example when I thight or large the page with mouse , ajax query start and rebuild datatable but i use server side datatable and this isn't good because is a waste of time, please help me:

this is my code of datatable

[CODE]

$(document).ready(function() {

var savedSelected;
var riga = getParam("riga");
var page = getParam("page");
var start = getParam("start");
var current = getParam("current");

FormValidation.init();
handleDatePickers();
var dataSet = [];

var oTable = $table.DataTable({
    "scrollY": "200px",
    "scrollCollapse": true,
    "processing": true,
    "serverSide": true,
    "paging": true,
    "info": false,
    "aLengthMenu": [
        [10, 50, 75, 100, 250, 500, -1],
        [10, 50, 75, 100, 250, 500, "All"]
    ],
    "pageLength": 50,
    //"pagingType": "numbers",
    "responsive": true,
    "autoWidth": false,
    "language": {
        "sEmptyTable": "Nessun dato presente nella tabella",
        "sInfo": "",
        "sInfoEmpty": "",
        "sInfoFiltered": "(filtrati da _MAX_ elementi totali)",
        "sInfoPostFix": "",
        "sInfoThousands": ".",
        "sLengthMenu": "<div class=elem_tot>Visualizza _MENU_ allievi su  <div class=totale></div></div>",
        "sLoadingRecords": "Caricamento...",
        "sProcessing": "Elaborazione...",
        "sSearch": "Cerca:",
        "sSearch[value]": "",
        "sZeroRecords": "La ricerca non ha portato alcun risultato.",
        "oPaginate": {
            "sFirst": "Inizio",
            "sPrevious": '<img src="assets/img/Arrow_SxO.svg" height="35" class="arrow_sx">',
            "sNext": '<img src="assets/img/Arrow_DxO.svg" height="35" class="arrow_dx">',
            "sLast": "Fine"
        },
        "oAria": {
            "sSortAscending": ": attiva per ordinare la colonna in ordine crescente",
            "sSortDescending": ": attiva per ordinare la colonna in ordine decrescente"
        },
    },
    "ajax": {
        "url": "ajax/mediaweb/getallievi.php",
        "dataSrc": function(json_data) {
            var start = document.getElementById("start_page");
            $(start).text(json_data.start + " , " + json_data.limit);
            var allievitot = document.getElementsByClassName("totale");
            $(allievitot).text(json_data.recordsTotal);
            return json_data.rows;

        },
    }, //end ajax call

    //function(oSettings, json) {

    //$("#table_paginate").appendTo('div#table_wrapper');

    "columns": [
        { responsivePriority: 1, "width": "75px", "data": "__rank", className: "dt-center" },
        { responsivePriority: 1, "width": "auto", "data": "Allievo", className: "dt-center myAnag" },
        { responsivePriority: 5, "width": "300px", "data": "MediaX", className: "dt-center myMediaX" }, //defaultContent: "<div id='mediaQuiz[]'></div>" },
        { responsivePriority: 3, "width": "300px", "data": "Media", className: "dt-center myMedia" }, //defaultContent: "<div id='mediaEsami[]'></div>" },
        { responsivePriority: 4, "width": "150px", "data": "Giudizio", className: "dt-center" },
        { responsivePriority: 6, "width": "150px", "data": "Patente", className: "dt-center" },
        { responsivePriority: 9, "width": "150px", "data": "ScadFr", className: "dt-center" },
        { responsivePriority: 7, "width": "75px", "data": "LTesti", className: "dt-center" },
        { responsivePriority: 8, "width": "75px", "data": "LAudio", className: "dt-center" }
    ],
    // "select": true,
    "createdRow": function(row, data, index) {
        fixPatenteAB1(row, data, index);
        fixDataEsame(row, data, index);
        setGiudizio(row, data, index);
        setFlags(row, data, index);


    },
    "rowCallback": function(row, data, index) {
        $.post("ajax/mediaweb/allieviscuola.php", { "id_allievo": data.Codice, "id_sedeClienteNeca": data.id_sedeClienteNeca }, function(data) {
            if (data.Presente === "0") {
                $(row).addClass("warning");
            }
        });
        $.post("ajax/mediaweb/schedeesamiallievi.php", { "id_allievo": data.Codice, "id_sedeClienteNeca": data.id_sedeClienteNeca }, function(data) {
            data = JSON.parse(data);
            row.cells[3].innerHTML = data.html;


        });
        $.post("ajax/mediaweb/schedequizallievi.php", { "id_allievo": data.Codice, "id_sedeClienteNeca": data.id_sedeClienteNeca }, function(html) {
            row.cells[2].innerHTML = html;
        });
        $.post("ajax/mediaweb/MediaEsame.php", { "id_allievo": data.Codice, "id_sedeClienteNeca": data.id_sedeClienteNeca }, function(data) {
            data = JSON.parse(data);

            var celle = row.cells[3].innerHTML;
            celle = celle.replace('</div>', '</div><div class="MediaEsame" style="position: absolute;top: 0;right: 0px;width: 50px;text-align: left;">' + data.html + '</div>"')

            row.cells[3].innerHTML = celle;
            setGiudizio(row, data, 0);

        });
        $.post("ajax/mediaweb/setData.php", { "id_allievo": data.Codice, "id_sedeClienteNeca": data.id_sedeClienteNeca }, function(data) {
            data = JSON.parse(data);
            setFormatdate(row, data, index);


        });

    },
    'stateSave': true,
    'stateSaveParams': function(settings, data) {
        data.selected = this.api().rows({ selected: true })[0];
    },
    'stateLoadParams': function(settings, data) {
        savedSelected = data.selected;
    },
    'initComplete': function(settings) {
        if (savedSelected != undefined) {
            this.api().rows(savedSelected).select();
            this.api().state.save();
        } else {
            this.api().rows(0).select();
        }

    },
    "stateDuration": 60 * 30
});

[/CODE]

Answers

  • colincolin Posts: 15,142Questions: 1Answers: 2,586

    Hi @Maxilboss93 ,

    It's because you've got ajax requests in your rowCallback function - this is called on every table draw, whether that be a resize, paging, or sorting. If that information is static, you could move it into createdRow perhaps,

    Cheers,

    Colin

  • Maxilboss93Maxilboss93 Posts: 33Questions: 6Answers: 0

    Hi Colin, However i tried to change in created row but isn't different, ajax start in all case of resize ...

  • Maxilboss93Maxilboss93 Posts: 33Questions: 6Answers: 0
    edited June 2019

    this is the structure of my php page, all pages are similar structure then this..

    <?php
    require('../../includes/config.php');
    require('../../includes/necaDB.php');
    
    $id_allievo = $_POST['id_allievo'];
    $id_sedeClienteNeca = $_POST['id_sedeClienteNeca'];
    
    
    $sql = 'SELECT
        sync.id_allievo AS id_allievo,
        COUNT(sync.id_allievo) AS Schede,
        TRUNCATE(AVG(sync.errori), 4) AS Media,
        LI.Domande AS Domande,
        IFNULL(LI.errori, 0) Errori
        FROM sync
        LEFT JOIN allievo A ON A.id_allievo = sync.id_allievo
        LEFT JOIN clientescuola CS ON CS.id_clienteScuola = A.id_clienteScuola
        LEFT join listato LI ON LI.tipo = A.listatoQuiz
        WHERE ((sync._Stato <> "D") AND (sync._Stato <> "X") AND (sync.tipo = "TipoEsame")) 
            AND CS.id_sedeClienteNeca = ' . $id_sedeClienteNeca . '
            AND sync.id_allievo = ' . $id_allievo . '
        GROUP BY sync.id_allievo';
    
    // $file = fopen('schedeEsami.log', 'w');
    // fwrite($file, 'Start ' . date("c") . PHP_EOL);
    $rows = NecaDB::arraySQL(null, $sql);
    // fwrite($file, 'After Query ' . date("c") . PHP_EOL);
    $result = array(
        'html' => '-',
        'Schede' => '0',
        'Media' => '0',
        'Errori' => '0'
    );
    
    if (isset($rows[0])) {
        $rows[0]['Media'] = floatval($rows[0]['Media']);
        $rows[0]['Schede'] = intval($rows[0]['Schede']);
        $rows[0]['Errori'] = intval($rows[0]['Errori']);
    
        $result['Media'] = $rows[0]["Media"];
        $result['Schede'] = $rows[0]["Schede"];
        $result['Errori'] = $rows[0]["Errori"];
    
        $numeroSchedeEsame = $rows[0]['Schede'] . "";
        $percentualeSchedaEsame =  ($numeroSchedeEsame/600)*100;
      
        //        $nW = (min($rows[0]['Media'], $rows[0]['Errori'] + 2) / ($rows[0]['Errori'] + 2)) * 100;
    
       if($rows[0]['Domande']==0){
        $percentualeEsameDomande=0;
        }
        else{
            $percentualeEsameDomande = ($rows[0]['Media']/ $rows[0]['Domande']) * 100;
            $percentualeEsameDomande = round( $percentualeEsameDomande, 1, PHP_ROUND_HALF_DOWN);
           
    
        }
        $nM = $rows[0]['Media'];
    
       /* if ($percentualeSchedaEsame> 100%){
    
        }*/
    
      
        //echo $numeroSchedeEsame;
        if (intval($numeroSchedeEsame) == 0) {
            $result['html'] = '-';
        } else {
            $result['html'] = '<div style="position: relative;height: 30px;">
            <div class="schedeEsame" style="position: absolute;top: 0px;left: 0;width: 40px;height: 30px;text-align: right;">' . $numeroSchedeEsame . '</div>
            <div style="position: absolute;width: calc(100% - 150px);top: 0;left: 50px;height: 30px;">
            <div style="top: 4px;left: 0px;width: 100%;background: #e1e4e9;position: absolute;height: 8px;border-radius: 4px; border: 1px solid #ffffff"></div>
            <div style="top: 4px;left: 0px;width:' . $percentualeSchedaEsame . '%;background: #47a035;position: absolute;height: 8px;border-radius: 4px; border: 1px solid #ffffff"></div>
            </div>
            <div class="percent" style="position: absolute;width: calc(100% - 150px);top: 0;right: 60px;height: 30px;">
            <div style="bottom:4px;right: 0px;width:100%;background: #e1e4e9;position: absolute;height: 8px;border-radius: 4px; border: 1px solid #ffffff"></div>
            <div  style="bottom:4px;right: 0px;width:' . $percentualeEsameDomande . '%;background: #47a035;position: absolute;height: 8px;border-radius: 4px; border: 1px solid #ffffff"></div>
            </div>';
           
        }
    }
    //fwrite($file, 'After Elab ' . date("c") . PHP_EOL);
    //fclose($file);
    
    echo json_encode($result, true);
    

    Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • colincolin Posts: 15,142Questions: 1Answers: 2,586

    The issue will be on the client side, it'll be making the ajax request. We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • Maxilboss93Maxilboss93 Posts: 33Questions: 6Answers: 0

    I can't get to work my testPage sorry, i can only take u all files of this problems,

    http://live.datatables.net/nutezezi/1/edit?html,css,js,console,output

    and php files are these:

    GETALLIEVI.PHP:

    [CODE]
    <?php

    require('../../includes/config.php');
    require('../../includes/necaDB.php');

    $start = $_GET["start"];
    $length = $_GET["length"];
    $search = $_GET["search"];
    $order = $_GET["order"];
    $columns =$_GET['columns'];

    $id_sedeClienteNeca = myLib::sessionParam("id_sedeClienteNeca", 0);
    $initRow = $start;
    $stepRowIndex = 1;
    $sqlOrder = 'ASC ';
    $asc = true;
    if (isOrderedByRank($order) && $order[0]['dir'] == 'desc') {
    $initRow = $start + $length;
    $stepRowIndex = -1;
    $sqlOrder = 'DESC ';
    $asc = false;
    }

    $limit = '';
    if ($length != '-1') {
    $limit ='LIMIT '.$start.','.$length;
    }
    $cSQLHead ='SELECT
    @curRow := @curRow + ' . $stepRowIndex . ' AS row_number,
    CS.id_sedeClienteNeca,
    A.id_allievo Codice,
    trim(concat(IFNULL(CS.cognome, ""), " ", IFNULL(CS.nome, ""))) Allievo,
    "0" Schede,
    "0" Media,
    "0" SchedeX,
    "0" MediaX,
    "Non valutabile" Giudizio,
    IFNULL(A.listatoQuiz, "") Patente,
    DATE_FORMAT(IFNULL(PR.dataVariazioneStato, "0000-00-00 00:00:00"), "%m-%d-%Y") ScadFr,
    IFNULL(LQ.prefisso, "IT") LTesti,
    IFNULL(LA.prefisso, "IT") LAudio,
    IFNULL(LI.errori, 0) Errori,
    LI.Domande,
    A.id_allievo Presente ';

    $cSQLPart2 = 'FROM allievo A
    left join clientescuola CS ON CS.id_clienteScuola = A.id_clienteScuola
    left join pratica PR ON PR.id_pratica = A.id_pratica
    left join mediaweb MW ON MW.id_mediaWeb = A.id_mediaWeb
    left join lingua LQ ON LQ.id_lingua = MW.linguaQuiz
    left join lingua LA ON LA.id_lingua = MW.linguaAudio
    left join listato LI ON LI.tipo = A.listatoQuiz
    JOIN (SELECT @curRow := ' . $initRow . ') r
    WHERE A._stato!="D" AND CS.id_sedeClienteNeca = ' . $id_sedeClienteNeca. ' ';

    if (isset($search['value']) && $search['value']!=""){
    $cSQLPart2 .='AND (CS.nome LIKE "%' . $search['value'] . '%" OR CS.cognome LIKE "%' .$search['value'] . '%") ';
    }
    $cSQLPart2.='ORDER BY ';
    if (isset($order[0]['column']) && $order[0]['column'] > 0) {
    $cSQLPart2 .= $columns[$order[0]['column']]['data'] . ' ' . $order[0]['dir'] . ', ';
    }
    $cSQLPart2.='Allievo ' . $sqlOrder .', ScadFr ' .$sqlOrder . ' ';

    if ($length != '-1') {
    $cSQLPart2 .= $limit;
    }

    $cSQLTot = 'SELECT COUNT(*) AS TOTAL FROM allievo A
    left join clientescuola CS ON CS.id_clienteScuola = A.id_clienteScuola
    WHERE A._stato!="D" AND CS.id_sedeClienteNeca = ' . $id_sedeClienteNeca;

    //echo $cSQL;
    $myDB = new NecaDB();
    $cSQL = $cSQLHead . $cSQLPart2;
    $data = $myDB->class_arraySQL($cSQLTot);
    $total = $data[0]['TOTAL'];
    //echo $total . ", " . $start . ", " . $length;
    //echo $cSQL;
    if (!$asc) $initRow = $total - $start;

    $recordsTotal=intval($total);
    $recordsFiltered=intval($total);
    $data = $myDB->class_arraySQL($cSQL, false, false, $initRow, $asc);

    $json_data = array(
    "recordsTotal" => intval( $total ),
    "recordsFiltered" => intval( $total ),
    "rows" => $data
    );

    echo str_replace('},{', '},' . "\n" . '{', json_encode($json_data, JSON_UNESCAPED_UNICODE));

    function isOrderedByRank($order) {
    return isset($order[0]['column']) && $order[0]['column'] == 0;
    }
    [/CODE]

  • Maxilboss93Maxilboss93 Posts: 33Questions: 6Answers: 0
    edited June 2019

    If u wanna see all other php file i' ll send u!

  • Maxilboss93Maxilboss93 Posts: 33Questions: 6Answers: 0

    problem solved, thanks a lot, there is a $dataTable.draw(); in a datatable resize function! sorry, im idiot!

This discussion has been closed.