MODAL CON DATATABLES

MODAL CON DATATABLES

iron_angelclpiron_angelclp Posts: 8Questions: 1Answers: 0

Estimados podrian por favor ayudarme.

Tengo el siguiente problema. Tengo un datatable donde muestro la información de clientes y en el cual tengo un botón donde muestro un modal con información ( Nombre y apellidos ). En este modal no solo necesito mostrar los nombres y apellidos de mi cliente, también tengo que mostrar un datatables con información detallada de la actividad de dicho cliente.

Mi pregunta seria: ¿ Existe alguna posibilidad que a través del ID de mi cliente pueda llamar a otra datatable con dicha información explicada anteriormente ?.

De ante mano muchas gracias por la ayuda que me den.

Saludos

Answers

  • rf1234rf1234 Posts: 2,801Questions: 85Answers: 406
    edited March 2017 Answer ✓

    Si, hay una solución for this. Sorry my Spanish is not good enough. Voy a continuar en inglés.
    "¿ Existe alguna posibilidad que a través del ID de mi cliente pueda llamar a otra datatable con dicha información explicada anteriormente ?."
    Yes, that can be done. Take a look at this blog: https://datatables.net/blog/2016-03-25
    You'll find this example there as well (Javascript):

    var usersEditor = new $.fn.dataTable.Editor( {
        ajax: {
            url: '../php/users.php',
            data: function ( d ) {
                var selected = siteTable.row( { selected: true } );
     
                if ( selected.any() ) {
                    d.site = selected.data().id;
                }
            }
        },
        table: '#users',
        fields: [ ... ]
    } );
    

    In this example the ID of a parent table (site Table - which is your "ID de mi cliente") is passed on to a child table (users Table - "otra datatable") as a $_POST variable (in case you are using PHP). The good news is that you can pass on much more than just the ID of the parent table to the child table by simply defining more "d. ..." variables.

  • iron_angelclpiron_angelclp Posts: 8Questions: 1Answers: 0

    Thank Rf1234 I going to try with that.

    Thank very much :D

  • rf1234rf1234 Posts: 2,801Questions: 85Answers: 406
    Answer ✓

    I'll keep my fingers crossed; in case you need further help just post some code examples to look at. ¡Buena suerte!

  • iron_angelclpiron_angelclp Posts: 8Questions: 1Answers: 0
    edited March 2017

    j

  • iron_angelclpiron_angelclp Posts: 8Questions: 1Answers: 0

    Well i see the code and I tried hard do the same think but with a button like this.

    var siteTable = $('#sites').DataTable( {
    dom: "Bfrtip",
    ajax: "../php/sites.php",
    columns: [
    { data: 'name' },
    { data: 'users', render: function ( data ) {
    return data.length;
    } },
    {defaultContent: "<button type='button' class='muestra btn btn-success' data-toggle='modal' data-target='#ate' ><i class='glyphicon glyphicon-paperclip'>Button</i></button>"}
    ],
    select: {
    style: 'single',
    },
    buttons: [
    { extend: "create", editor: siteEditor },
    { extend: "edit", editor: siteEditor },
    { extend: "remove", editor: siteEditor }
    ]
    } );

    I put that button and i get the ID of the client

    function ( d ) {
    var selected = siteTable.row( { selected: true } );
    if ( selected.any() ) {
    d.site = selected.data().id;
    }

    but in this function get the ID from the selected row i need that function get but the Id from my button if you know how to do that i going to appreciate so much your help.

  • rf1234rf1234 Posts: 2,801Questions: 85Answers: 406
    edited March 2017 Answer ✓

    Maybe something like this could work.

    define as a global JavaScript variable:
    var idPassed;

    var YourTable = $('#YourTable').DataTable( {
    ajax: {
      url: '...',
      type: 'POST',            
      data: function ( d ) {
        $('#YourTable').on( 'click', '.muestra', function () {
              idPassed = YourTable.row( $(this).closest('tr') ).data().idFromButton;
          } );
          d.id = idPassed;
      }
    },
    
  • iron_angelclpiron_angelclp Posts: 8Questions: 1Answers: 0

    My friend i tried with that.

    var YourTable = $('#YourTable').DataTable( {
    ajax: {
    url: '...',
    type: 'POST',
    data: function ( d ) {
    $('#YourTable').on( 'click', '.muestra', function () {
    idPassed = YourTable.row( $(this).closest('tr') ).data().idFromButton;
    Here the console log show me the Id
    } );
    Here the console log don't show me the id
    d.id = idPassed; -> Here this value don't get the id but if i put this code inside the function onclick get the idPassed.
    }

    I see that. Cuase i use the console.log(); and when i put the IdPassed; inside of the function the console.log show me the id but out of the function don't show and my question is. How can I pass the ID from the function to the another function?.

    I appreciate your answer. Thank you.

  • rf1234rf1234 Posts: 2,801Questions: 85Answers: 406
    Answer ✓

    Normally you call a function and pass the variable. Working with datatables' predefined callbacks etc. it is not always possible to pass a variable into one of these functions.
    I therefore use global variables in these cases which I can access from everywhere.
    Consider this code. You see I use a variable called "ck" (a cookie read outside of this function). I cannot pass this variable into the function below. Therefore I defined it previously as a global variable. If you don't know how global variables work in Javascript please read this: https://www.w3schools.com/js/js_scope.asp or search Google for Javascript scope etc.

    Using Datatables you have the same situation in PHP: In many cases you can't pass a variable in from outside. Hence you use the global variables like $_POST, $_SESSION etc. which you can access everywhere

    contractCredEditor
    .on( 'postSubmit', function ( e, json, data, action ) {
        //after submitting the contract the submitted contract needs to be 
        //selected automatically 
        if (action === 'create') {
            if (ck > '') {
                var selectedId = '#' + json.data[0].DT_RowId; //"#row_99"
                setTimeout(function(){ contractCredTable.row(selectedId).select(); }, 500);
                var id; 
                var table;
                if (typeof ck.rfp !== 'undefined' ) { //coming from RfP
                    id = ck.rfp.id;
                    table = 'rfp';
                } else {   //coming from Proposal
                    id = ck.proposal.id;
                    table = 'proposal';
                }
                $.ajax({
                    type: "POST",
                    url: 'actions.php?action=RfpOrProposalBasedContract',
                    async: true,
                    data: {
                        table: table,
                        id: id,
                        contractId: selectedId.substring(5) //only after "#row_"
                    },
                    dataType: "json"
                });
            }
        }
    });
    
  • iron_angelclpiron_angelclp Posts: 8Questions: 1Answers: 0

    I defined the idPassed as a global Javascript Variable but I have that problem, that i explained to you in the last post. And I try to see with console.log(); But nothing and I am sorry Cause i didn't explain you I put the global variable.

  • rf1234rf1234 Posts: 2,801Questions: 85Answers: 406
    Answer ✓

    Sorry, but I need to see the exact code that you are using, both Javascript and PHP. And if possible the HTML. Otherwise I don't think I can be of help for you.

  • iron_angelclpiron_angelclp Posts: 8Questions: 1Answers: 0

    Ok, Just i use the example for the datatables for try this and then I put in my code but I can show u my code without this example.

    this the javascript code ( is not full ). here is the code where i show the all client i have in my database

    var listar = function(){
    $("#cuadro2").slideUp("slow");
    $("#cuadro1").slideDown("slow");

        var table = $("#dt_cliente").DataTable({
                scrollY: "300px",
                scrollCollapse: true, 
        destroy:true,
                searching: true,
                sort: true,
        ajax:{
        method:"POST",
        url: "modulos/listar.php"
                },
            "columns":[
                    {"defaultContent": "<button type='button' class='muestra btn btn-success' data-toggle='modal' data-target='#ate' ><i class='glyphicon glyphicon-paperclip'></i></button>"},
                    {"data":"rut"},
                    {"data":"nombres"},
                    {"data":"apellidos"},
                    {"data":"f_nace"},
                    {"data":"sexo"},
                    {"data":"mail"},
                    {"data":"direccion"},
                    {"data":"fono"},
                    {"data":"S_salud"},
                    {"data":"Ocupacion"},
            {"defaultContent": "<button type='button' class='ficha btn btn-info' >Ficha</button> <button type='button' class='caratula btn btn-warning'>Caratula</button>"}, 
                    {"defaultContent": "<button type='button' class='editar btn btn-primary' data-toggle='modal' data-target='#paciente'><i class='fa fa-pencil-square-o'></i></button> <button type='button' class='eliminar btn btn-danger' data-toggle='modal' data-target='#modalEliminar' ><i class='fa fa-trash-o'></i></button>"}
                ],
                "language": idioma_espanol,
                "dom":  "<'row'<'form-inline' <'col-sm-offset-5'B>>>"
                     +"<'row' <'form-inline' <'col-sm-1'f>>>"
                     +"<rt>"
                     +"<'row'<'form-inline'"
                     +" <'col-sm-6 col-md-6 col-lg-6'l>"
                     +"<'col-sm-6 col-md-6 col-lg-6'p>>>",//'Bfrtip',
                "buttons":[                 
                    {
                        text:      '<i class="fa fa-user-plus" data-toggle="modal" data-target="#paciente"></i>',
                        titleAttr: 'Agregar Usuario',
                        className: 'btn btn-primary',
                        action:     function(){
                                    limpiar_datos();
                                    agregar_nuevo_usuario();
                        }
                    },
                    {
                        extend:    'excelHtml5',
                        text:      '<i class="fa fa-file-excel-o"></i>',
                                 className: 'btn btn-success',
                        titleAttr: 'Excel'
                    },
                    {
                        extend:    'csvHtml5',
                        text:      '<i class="fa fa-file-text-o"></i>',
                                className: 'btn btn-success',
                        titleAttr: 'CSV'
                    },
                    {
                        extend:    'pdfHtml5',
                        text:      '<i class="fa fa-file-pdf-o"></i>',
                                className: 'btn btn-danger',
                        titleAttr: 'PDF'
                    }
                ]
            });
    

    $('#dt_cliente tbody').on('click','button.muestra', function () {
    var data = table.row($(this).parents("tr")).data();
    console.log(data);
    var idusuario = $("#Frmate #idusuario").val( data.id_p ),
    nombres = $("#Frmate #nombres").val( data.nombres ),
    apellidos = $("#Frmate #apellidos").val( data.apellidos);

             } );             
    

    $('#dt_cliente tbody').on('click','button.ficha', function () {
    var data = table.row($(this).parents("tr")).data();
    console.log(data.id_p);
    window.open('php/Ficha.php?id='+(data.id_p));
    } );

    $('#dt_cliente tbody').on('click','button.caratula', function () {
    var data = table.row($(this).parents("tr")).data();
    console.log(data.id_p);
    window.open('php/caratula.php?id='+(data.id_p));
    } );

        function filtrar(i) {
          $('#dt_cliente').DataTable().column(i).search(
           $('#col'+i+'_filter').val()).draw();
            }
    
            $('input.column_filter').on( 'keyup click', function () {
            filtrar( $(this).parents('td').attr('data-column') );
            } );
    
            obtener_data_editar("#dt_cliente tbody", table);
            obtener_id_eliminar("#dt_cliente tbody", table);
        }
    

    with this i get the data of patients through php (client).

    <?php

    include ("conexion.php");
    
    $query = "SELECT * FROM paciente ORDER BY id_p ASC;";
    $resultado = mysqli_query($conexion, $query);
    

    if(!$resultado){

     die("Error");
    

    }else{
    while($data = mysqli_fetch_assoc($resultado)){
    $arreglo["data"][] = array_map("utf8_encode", $data);

     }
     echo json_encode($arreglo);
    

    }

    mysqli_free_result($resultado);
    mysqli_close($conexion);

    if you know how can u help i appreciate and thank so much for the help i feel i so close of the solution,

  • iron_angelclpiron_angelclp Posts: 8Questions: 1Answers: 0

    dearle friend I found the solution for this :D thank to you for your help !!!

  • rf1234rf1234 Posts: 2,801Questions: 85Answers: 406
    Answer ✓

    ok, great that it works now.

This discussion has been closed.