Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

David Silveira_63904

Datatable Performance - Problema ao carregar dados

Recommended Posts

Olá, amigos...

 

Estou com um problema no meu DataTable ao carregar grande massa de dados. Acontece que ele chega fica processando e acaba travando o navegador.

 

Eu analisando o codigo percebi que está faltando um LIMIT no select, porém não sei como criar esse LIMIT sem que eu perca a paginação e a pesquisa que posso fazer.

 

Gostaria de uma ajuda para resolver meu problema, sou novo na programação mais enfim vivendo e aprendendo.

 

 

Versão Datatable:

 

/*
* File: jquery.dataTables.min.js
* Version: 1.6.2
* Author: Allan Jardine (www.sprymedia.co.uk)
* Info: www.datatables.net
*
* Copyright 2008-2010 Allan Jardine, all rights reserved.
*
* This source file is free software, under either the GPL v2 license or a
* BSD style license, as supplied with this software.
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*/

 

 

Logo abaixo tem meu codigo:

 

<script type="text/javascript">

$(document).ready(function(){
/* setup navigation, content boxes, etc... */
Administry.setup();
/* datatable */
$('#example').dataTable();
/* expandable rows */
Administry.expandableRows();
});
</script>
<section class="column width6 first">
<h1>Lista de Contatos</h1>
<div class="box box-info">Utilize a tabela abaixo para visualizar suas lista de contatos</div>
<table class="display stylized" id="example">
<thead>
<tr>
<th>Nome do Contato</th>
<th>Lista de Contato</th>
<th>DDI</th>
<th>DDD</th>
<th>Numero</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<?php
$cclista = mysql_query("select * from contatos
left join lista_contatos on (contatos.idlistacontatos=lista_contatos.idlista_contatos)
left join clientes on (lista_contatos.cliente_id=clientes.idclientes)
where clientes.idclientes='".$_SESSION['logado']."' order by lista_contatos.nome_lista $sLimit") or print(mysql_error());
while($ccl = mysql_fetch_array($cclista)){
?>
<tr class="gradeA">
<td><?=utf8_encode($ccl['nome_contato']);?></td>
<td><?=utf8_encode($ccl['nome_lista']);?></td>
<td><?=$ccl['cod_pais'];?></td>
<td><?=$ccl['cod_estado'];?></td>
<td class="center"><?=$ccl['numero_contato'];?></td>
<td class="center"><a href="?pg=contato_edit&id=<?=$ccl['idcontatos'];?>" class="linkazul">Editar</a> | <a href="javascript:ConfirmaExcluiContato('<?=$ccl['idcontatos'];?>');" class="linkazul" style="color:#C00">Excluir</a></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<th>Nome do Contato</th>
<th>Lista de Contato</th>
<th>DDI</th>
<th>DDD</th>
<th>Numero</th>
<th>Ações</th>
</tr>
</tfoot>
</table>
</section>
<!-- End of Left column/section -->
<a href="exportar_contatos.php"><img src="img/excel.jpg" alt="Exportar dados" width="64" height="64" title="Exportar dados" border="0" /></a>
<script type="text/javascript" SRC="js/administry.js"></script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá, Lucas tudo bem?

 

Então pelo que eu entendi, esse ajax ele faz com que o processamento das informações fique do lado servidor e não do usuário, acho que é isso.

 

Nesse caso vou tem que chamar o codigo AJAX

 

$(document).ready(function() {
$('#example').dataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
Assim cria um array na pagina...
Minha dúvida agora é, o SELECT como fica pra montar isso? poderia me ajudar? muito obrigado!

Compartilhar este post


Link para o post
Compartilhar em outros sites

Você deve configurar sua aplicação para processamento Server-side, sempre que fizer uma paginação, filtro, ordem etc.. sua aplicação deve ir no Server e trazer o resultado, da forma que está (Client-side) ele baixar o DB de uma vez, e faz tudo ali do lado do cliente causando lentidão devido o grande volume de dados.

 

Pesquise por DataTables Server-side

 

exemplo completo server-side usando mysqli: https://datatables.net/development/server-side/php_mysqli

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá, Lucas e Hugo. Bom dia meus amigos!

 

Então funcionou a aplicação e está igual um foguete..rsrsrs

 

Só ficou agora de eu amarar a sessão de cada usuário no "server_processing.php", e aba do front ações que na verdade seria editar e excluir.

 

No meu antigo estava assim:

 

 

 

<td class="center"><a href="?pg=contato_edit&id=<?=$ccl['idcontatos'];?>" class="linkazul">Editar</a> | <a href="javascript:ConfirmaExcluiContato('<?=$ccl['idcontatos'];?>');" class="linkazul" style="color:#C00">Excluir</a></td>

 

 

Teria um caminha para me orientar?

 

 

Ficou assim meu "server_processing.php":

 

 

<?php
/**
* Script: DataTables server-side script for PHP 5.2+ and MySQL 4.1+
* Notes: Based on a script by Allan Jardine that used the old PHP mysql_* functions.
* Rewritten to use the newer object oriented mysqli extension.
* Copyright: 2010 - Allan Jardine (original script)
* 2012 - Kari Söderholm, aka Haprog (updates)
* License: GPL v2 or BSD (3-point)
*/
mb_internal_encoding('UTF-8');
/**
* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
$aColumns = array( 'idcontatos', 'nome_contato', 'nome_lista', 'cod_pais', 'cod_estado', 'numero_contato' );
// Indexed column (used for fast and accurate table cardinality)
$sIndexColumn = 'idcontatos';
// DB table to use
$sTable = 'contatos';
// Database connection information
$gaSql['user'] = ' ';
$gaSql['password'] = ' ';
$gaSql['db'] = ' ';
$gaSql['server'] = ' ';
$gaSql['port'] = 3306; // 3306 is the default MySQL port
// Input method (use $_GET, $_POST or $_REQUEST)
$input =& $_GET;
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/
/**
* Character set to use for the MySQL connection.
* MySQL will return all strings in this charset to PHP (if the data is stored correctly in the database).
*/
$gaSql['charset'] = 'utf8';
/**
* MySQL connection
*/
$db = new mysqli($gaSql['server'], $gaSql['user'], $gaSql['password'], $gaSql['db'], $gaSql['port']);
if (mysqli_connect_error()) {
die( 'Error connecting to MySQL server (' . mysqli_connect_errno() .') '. mysqli_connect_error() );
}
if (!$db->set_charset($gaSql['charset'])) {
die( 'Error loading character set "'.$gaSql['charset'].'": '.$db->error );
}
/**
* Paging
*/
$sLimit = "";
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
$sLimit = " LIMIT ".intval( $input['iDisplayStart'] ).", ".intval( $input['iDisplayLength'] );
}
/**
* Ordering
*/
$aOrderingRules = array();
if ( isset( $input['iSortCol_0'] ) ) {
$iSortingCols = intval( $input['iSortingCols'] );
for ( $i=0 ; $i<$iSortingCols ; $i++ ) {
if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
$aOrderingRules[] =
"`".$aColumns[ intval( $input['iSortCol_'.$i] ) ]."` "
.($input['sSortDir_'.$i]==='asc' ? 'asc' : 'desc');
}
}
}
if (!empty($aOrderingRules)) {
$sOrder = " ORDER BY ".implode(", ", $aOrderingRules);
} else {
$sOrder = "";
}
/**
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$iColumnCount = count($aColumns);
if ( isset($input['sSearch']) && $input['sSearch'] != "" ) {
$aFilteringRules = array();
for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' ) {
$aFilteringRules[] = "`".$aColumns[$i]."` LIKE '%".$db->real_escape_string( $input['sSearch'] )."%'";
}
}
if (!empty($aFilteringRules)) {
$aFilteringRules = array('('.implode(" OR ", $aFilteringRules).')');
}
}
// Individual column filtering
for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
$aFilteringRules[] = "`".$aColumns[$i]."` LIKE '%".$db->real_escape_string($input['sSearch_'.$i])."%'";
}
}
if (!empty($aFilteringRules)) {
$sWhere = " WHERE ".implode(" AND ", $aFilteringRules);
} else {
$sWhere = "";
}
/**
* SQL queries
* Get data to display
*/
$aQueryColumns = array();
foreach ($aColumns as $col) {
if ($col != ' ') {
$aQueryColumns[] = $col;
}
}
$sQuery = "
SELECT nome_contato, nome_lista, cod_pais, cod_estado, numero_contato, idcontatos `".implode("`, `", $aQueryColumns)."`
FROM `".$sTable."`left join lista_contatos on (contatos.idlistacontatos=lista_contatos.idlista_contatos)".$sWhere.$sOrder.$sLimit;
$rResult = $db->query( $sQuery ) or die($db->error);
// Data set length after filtering
$sQuery = "SELECT FOUND_ROWS()";
$rResultFilterTotal = $db->query( $sQuery ) or die($db->error);
list($iFilteredTotal) = $rResultFilterTotal->fetch_row();
// Total data set length
$sQuery = "SELECT COUNT(`".$sIndexColumn."`) FROM `".$sTable."`";
$rResultTotal = $db->query( $sQuery ) or die($db->error);
list($iTotal) = $rResultTotal->fetch_row();
/**
* Output
*/
$output = array(
"sEcho" => intval($input['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array(),
);
while ( $aRow = $rResult->fetch_assoc() ) {
$row = array();
for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
if ( $aColumns[$i] == 'version' ) {
// Special output formatting for 'version' column
$row[] = ($aRow[ $aColumns[$i] ]=='0') ? '-' : $aRow[ $aColumns[$i] ];
} elseif ( $aColumns[$i] != ' ' ) {
// General output
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
?>

 

 

Muito obrigado mesmo...

Compartilhar este post


Link para o post
Compartilhar em outros sites

Mano aqui tem exemplos de edição https://editor.datatables.net/examples/index.html

 

não sei se na API tem como chama a função "delete" por exemplo de um button qualquer (acredito que tenha).

 

dai.. no seu HTML normal..

<div class="actions">

<?php
  if ($_SESSION['grupo'] == 'admin'){
?>
  <input type="button" value="Delete" id="btnDelete" />
<?php
  }
?>

</div>

agora se não há como, ou por questões de designer você queira seguir no padrão do plugin

pode tentar assim.

 

jquery.exemplo.php

<?php
header("Content-type: application/javascript; charset=utf-8");
?>

$('#example').DataTable({
 dom: "Tfrtip",
 ajax: {
 url: "../php/staff.php",
 type: "POST"
},
 serverSide: true,
 columns: [
  { data: "first_name" },
  { data: "last_name" },
  { data: "position" },
  { data: "office" },
  { data: "start_date" },
  { data: "salary", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) }
 ],
 tableTools: {
 sRowSelect: "os",
 aButtons: [
  { sExtends: "editor_create", editor: editor }, // button NOVO
  <?php if ($_SESSION['grupo'] == 'admin'){ ?>
  { sExtends: "editor_edit",   editor: editor }, // button EDITAR
  { sExtends: "editor_remove", editor: editor } // button DELETAR
  <?php } ?>
 ]
 }
});
<script type="text/javascript" src="jquery.exemplo.php"></script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.