Crear paginación con PHP y Jquery

En este tutorial voy a explicar como crear una paginación con PHP y Jquery.
Añadiremos un extra, que se podrá filtrar.

Librerías que necesitaremos para llevar a cabo la paginación.

Yo al plugin le he añadido un extra, que indique el total de resultados.
Si se lo queréis añadir ir a al método _draw situaros en la linea 175 y añadir el siguiente codigo

// Añade el total de registro y muestra los registros actuales x - x de X
// @date 2015-09-01
var ttreg = (o.currentPage+1)*o.itemsOnPage;
if(ttreg > o.items){
  ttreg = o.items;
}
$(''+(o.itemsOnPage*(((o.currentPage+1)-1))+1)+' - '+ttreg+' de '+o.items+'').appendTo(this);

Codigo HTML

<div id="pagi1">
	<form class="searchform">
		<label>Nombre</label>
		<input type="text" name="nombre_user">
		<label>Email</label>
		<input type="text" name="email_user">

		<button class="btn-search-new">Filtrar</button>
		<input type="hidden" name="search-url" value="ajax/user.php"> -&gt; Url donde se procesara la consulta para el filtro
		<input type="hidden" name="search-user-form" value="1">
	</form>
	<br>
	<div class="search-div-table">
		<table class="table">
			<thead>
				<tr>
					<th>Col1</th>
					<th>Col2</th>
					<th>Col3</th>
				</tr>
			</thead>
			<tbody>

			</tbody>
		</table>
	</div>
	<input type="hidden" name="totalRecords" value="0"> -&gt; Total registros
	<input type="hidden" name="totalRecordsPage" value="10"> -&gt; Total registros por página
	<input type="hidden" name="getUrl" value="ajax/user.php"> -&gt; Url donde se harán las peticiones cuando pasemos de página
	<br>
	<div class="smpagination"></div>
</div>
</code>Lenguaje del código: HTML, XML (xml)

Codigo PHP

header('Content-Type: application/json');

chdir('../');
require('class/class.php');

$db = new db();
$db->_connect();

if(isset($_GET['search-user-form'])){
	$return = array();

	$recordsPerPage = 6;

	$user = $_GET['nombre_user'];
	$email = $_GET['email_user'];

	if(!empty($user) || !empty($email)):

		$query= "SELECT nombre,email,password FROM tuser WHERE nombre LIKE '%$user%' AND email LIKE '%$email%' ";
		$res = $db->conexion->query($query);
		$t_records = $res->num_rows;

		if($t_records > 0):

			$n_page = isset($_GET['page']) ? $_GET['page'] : 1;
			if($n_page == 1){
				$p_inicio = 0;
			}else{
				$p_inicio = ($n_page - 1) * $recordsPerPage;
			}

			$query2 = $query." LIMIT $p_inicio,$recordsPerPage";
			$res2 = $db->conexion->query($query2);

			$return['html'] = '';
			while ($f = $res2->fetch_assoc()) {
				$return['html'] .= '';
					$return['html'] .= ''.utf8_encode($f['nombre']).'';
					$return['html'] .= ''.$f['email'].'';
					$return['html'] .= ''.$f['password'].'';
				$return['html'] .= '';
			}

			$return['totalRecords'] = $t_records;
			$return['totalRecordsPage'] = $recordsPerPage;
		else:
			$return['error'] = true;
			$return['error_t'] = 2;
			$return['error_msg'] = 'No hay resultados';
		endif;

	else:
		$return['error'] = true;
		$return['error_t'] = 3;
		$return['error_msg'] = 'Tienes que rellenar al menos un campo';
	endif;

	echo json_encode($return);
}

Aquí es donde se complica mas la cosa con el código javascript.

Esto es para poder filtrar los resultados

$('.contenedor').on('click','.btn-search-new',function(event){
	event.preventDefault();
	var node = $(this).parent().parent();

	var form = node.children('form');
	var table = node.find('div table');
	var pagnav = node.children('.smpagination');

	var inurl = form.children('input[name=search-url]').val();
    if(inurl.indexOf('?') >= 0){
        var url = inurl+'&'+form.serialize();
    }else{
        var url = inurl+'?'+form.serialize();
    }

	if(typeof url != 'undefined'){
		infeLoading();
		$.getJSON(url, function(data) {
			infeLoading('hidden');
			if(data.error){
				table.parent().removeAttr('style');
				table.children('tbody').html('');
				pagnav.pagination('destroy');
				infeError(node,data.error_msg,data.error_t);
			}else{
				node.children('input[name=totalRecords]').val(data.totalRecords);
				node.children('input[name=totalRecordsPage]').val(data.totalRecordsPage);
				table.children('tbody').html(data.html);

				infePagination('#'+node.attr('id'),true);
			}
		})
		.fail(function( jqxhr, textStatus, error ) {
		    var err = textStatus + ", " + error;
		    console.log(err);
		});
	}
});

Y aquí esta la función donde se crea la paginación, al hacer click en el numero de página vaya a buscar los registros de la página.

function infePagination(pagination,refresh,pagStatic){
var refresh = typeof refresh !== 'undefined' ? refresh : false;
var pagStatic = typeof pagStatic !== 'undefined' ? pagStatic : false;

var node = $(pagination);
var error = node.children('.alert');
var trecords = parseInt(node.children('input[name=totalRecords]').val());

var form = node.children('.searchform');
var table = node.find('div table');
var items = table.find('tbody tr');

var pagnav = node.children('.smpagination');

if(refresh){
pagnav.pagination('destroy');
}

if(trecords > 0){
//Eliminar si ha habido error antes
if(error.length > 0){
error.removeClass().addClass('alert').text('');
}

var trecordsPerPage = 15;
if(node.children('input[name=totalRecordsPage]').length > 0){
var trecordsPerPage = parseInt(node.children('input[name=totalRecordsPage]').val());
}

//Si hay menos no creamos el paginador
if(trecords > trecordsPerPage){
var searchform = typeof form !== 'undefined' ? form.serialize() : '';
var url = node.children('input[name=getUrl]').val();

//Verificar que haya url o si es estatico
if(typeof url != 'undefined' || pagStatic){
//Hacer la tabla estatica en caso de que en una pagina(de la tabla) hubiera menos resultados
if(pagStatic){
items.slice(trecordsPerPage).hide();
}else{
var htable = table.children('tbody').height();
table.parent().css('height',htable+20);
}

//Crear el paginador
pagnav.pagination({
prevText: '«',
nextText: '»',
items: trecords,
itemsOnPage: trecordsPerPage,
cssStyle: 'compact-theme',
onPageClick: function(pageNum,event){
event.preventDefault();
//Asociar al evento de onPageClick hacer una busqueda
//para la siguiente pagina

if(pagStatic){
var showFrom = trecordsPerPage * (pageNum - 1);
var showTo = showFrom + trecordsPerPage;

items.hide().slice(showFrom, showTo).show();
}else{
//Crear la url donde se hará la petición con los parámetros adecuados
//Añadiremos el form de filtrado también
var inurl = form.children('input[name=search-url]').val();
if(inurl.indexOf('?') >= 0){
var url = inurl+'&'+form.serialize()+'&page='+pageNum;
}else{
var url = inurl+'?'+form.serialize()+'&page='+pageNum;
}

infeLoading('Cargando registros....');
$.getJSON(url, function(data) {
infeLoading('hidden');
if(data.error){
table.parent().removeAttr('style');
table.children('tbody').html('');
pagnav.pagination('destroy');
infeError(node,data.error_msg,data.error_t);
}else{
table.children('tbody').html(data.html);
}
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log(err);
});
}
}
});
}
}
}else{
table.parent().removeAttr('style');
table.children('tbody').html('');
pagnav.pagination('destroy');
infeError(node,'No hay resultados',2);
}
}



El ejemplo contra la base de datos no es 100% funcional porque no se conecta a una BD.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Captcha cargando...

Scroll al inicio