Problem with append after ajax

Problem with append after ajax

Maxilboss93Maxilboss93 Posts: 33Questions: 6Answers: 0
edited June 2019 in Free community support

i have a problem with an ejax result, i have my datatable with their rows,

NUM. | COGNOME E NOME | Schede ESERCIZI Errori | Schede ESAME Errori |

All rows are loading correct but i have a problem with row.cells[3] because i have 2 php page how response of ajax to compile the 3 fields of column, "schede" and "esami" are compiled with this code:

  "rowCallback": function(row, data, index) {
     
            $.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;
                setGiudizio(row, data, 0);

            });

the third fields ("Errori") is a response ajax of this:
            $.post("ajax/mediaweb/MediaEsame.php", { "id_allievo": data.Codice, "id_sedeClienteNeca": data.id_sedeClienteNeca }, function(data) {
                data = JSON.parse(data);               

            });


  data= MediaErrori: 0 , <div style="position: absolute;top: 0;right: 0px;width: 50px;text-align: left;">' . $mediaEsameFormattato . </div>

how can i append this last data to first data with processing html of div?

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

Replies

  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    Hi @Maxilboss93 ,

    First, I would suggest using cell().data() rather than row.cells[3].innerHTML, since DataTables wouldn't know about the change and wouldn't sort/search correctly.

    If you're just appending, can't use get the existing value first - either with cell().data() or your row.cells[3].innerHTML.

    If that doesn't help, 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

    $(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_Sx.svg' class='arrow_sx' >",
                "sNext": "<img src='assets/img/Arrow_Dx.svg' 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;
                setGiudizio(row, data, 0);
    
            });
            $.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);
    
    
                /*<div style="position: absolute;top: 0;right: 0px;width: 50px;text-align: left;">' . $mediaEsameFormattato . '</div>*/
    
    
    
            });
        },
        '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
    });
    

    Hort to use cell().data()?

  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    There's example on its page that are worth looking at. Also, see here.

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

    Sorry but i want to take the data one for the row in all the position of row.cells[3] but if i use the append the table append all data in all rows, how i take one for rows data in addition to data that there was first?
    For example i want, (your example) in the same field ("london, 35"), in my case i want in the same field 2 result of 2 different ajax.

    one results of this php page

    <?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%){

    }*/
    if ($nM == 0) {
        $nM = "";
        $mediaEsameFormattato = "";
    } else {
        $mediaEsameFormattato = number_format($nM, 1);
        $mediaEsameFormattato = round( $mediaEsameFormattato, 1, PHP_ROUND_HALF_DOWN);
    }
    //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>
        </div>';
    }
    

    }
    //fwrite($file, 'After Elab ' . date("c") . PHP_EOL);
    //fclose($file);

    echo json_encode($result, true);

    and second result in this php other page:

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

    $id_allievo = $_POST['id_allievo'];
    $id_sedeClienteNeca = $_POST['id_sedeClienteNeca'];

    $sql= "SELECT AVG(Media) as MediaErrori FROM (SELECT errori as Media FROM sync WHERE id_allievo= ". $id_allievo . " AND tipo = 'TipoEsame' ORDER BY sync.dataFine DESC Limit 15)as MediaErrori";

    $rows = NecaDB::arraySQL(null, $sql);

    if (isset($rows[0])) {
    $rows[0]['MediaErrori'] = floatval($rows[0]['MediaErrori']);
    $nM = $rows[0]['MediaErrori'];

    $result['MediaErrori'] = $rows[0]["MediaErrori"];
    }

    if ($nM == 0) {
    $nM = "";
    $mediaEsameFormattato = "";
    } else {
    $mediaEsameFormattato = number_format($nM, 1);
    $mediaEsameFormattato = round( $mediaEsameFormattato, 1, PHP_ROUND_HALF_DOWN);
    }

    $result['html'] =$mediaEsameFormattato;
    

    echo json_encode($result, true);

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

    The result of this code: row.cells[3].append(data.html);

    its this:
    6 (there is a graphic)

    "'<div 'style="position: relative;top: 0;right: 0px;width: 50px;text-align: left;">24.2</div>'"

    but i want : 6 ( graphic) 24

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

    i changed the element , i Load the div empty in the first php page and after i use
    var mediaesame = document.getElementsByClassName("MediaEsame");
    $(mediaesame).append(data.html);
    but if i use this method the table load all results in all rows.

  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    That's a lot of code, but the easiest thing here would be to create that test page that I requested before, or link to your page. That way we can see what's going on and understand it better.

    Cheers,

    Colin

  • Maxilboss93Maxilboss93 Posts: 33Questions: 6Answers: 0

    nothing, i have the solutions, i used:
    var celle = row.cells[3].innerHTML;
    celle = celle.replace('</div>', '</div>

    ' + data.html + '

    "')

                row.cells[3].innerHTML = celle;
    

    and this is the solution.

This discussion has been closed.