Jump to content
Fábio Peixeiro

PHP + simplePagination.js

Recommended Posts

Fábio Peixeiro

Boa tarde dando continuação ao tópico, estou aqui com um problema que não consigo resolver. Tenho o seguinte Código.

Spoiler

<?php
require("C:/xampp/htdocs/connect.php");
$c = $_REQUEST['a'];

//for total count data
$countSql = "SELECT COUNT(cd_p) FROM participantes";
$tot_result = mysqli_query($connect, $countSql);
$row = mysqli_fetch_row($tot_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);

//for first time load data
if (isset($_GET["page"])) {
    $page = $_GET["page"];
} else {
    $page = 1;
};
$start_from = ($page - 1) * $limit;
$sql = "SELECT cd_p, nome, morada FROM participantes ORDER BY cd_p ASC LIMIT $start_from, $limit";
$rs_result = mysqli_query($connect, $sql);

?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
    <script src="pagination/dist/jquery.simplePagination.js"></script>
    <link href="pagination/dist/simplePagination.css" rel="stylesheet">
    <script src="part_ati/js/script.js"></script>
    <title></title>
    <script>
    </script>
</head>
<body>
<div class="container" style="padding-top:20px;">
    <input type="hidden" name="cd" id="cd" value="<?php echo $c; ?>">
    <div align="center">
        <p>
            <input type="text" name="search" id="search" class="form-control"
                   style="max-width: 200px; text-align: center" placeholder="Procurar por nome">
        </p>
    </div>
    <div id="partTable" style=" overflow: auto">
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th width="5%">#</th>
                <th width="50%">Nome</th>
                <th width="35%">Morada</th>
                <th width="10%">Estado</th>
            </tr>
            </thead>
            <tbody id="target-content">
            <?php
            while ($row = mysqli_fetch_assoc($rs_result)) {
                $p = $row['cd_p'];
                $query2 = "SELECT participantes.cd_p, participantes_atividades.cd_ati FROM participantes_atividades, participantes WHERE participantes.cd_p = participantes_atividades.cd_p AND participantes_atividades.cd_ati = $c AND participantes_atividades.cd_p = $p ORDER BY cd_p ASC";
                $result2 = mysqli_query($connect, $query2) or die (mysqli_error($connect));
                ?>
                <tr class="table-search">
                    <td><?php echo $row["cd_p"]; ?></td>
                    <td><?php echo $row["nome"]; ?></td>
                    <td><?php echo $row["morada"]; ?></td>
                    <td><?php
                        if ($row2 = mysqli_fetch_array($result2))
                            echo '<a data-id=', $row['cd_p'], ' name="bRemover" class="btn btn-danger btn-xs bRemover-data" >Remover</a>';
                        else echo '<a data-id=', $row['cd_p'], ' name="bAdicionar" class="btn btn-primary btn-xs bAdicionar-data" >Adicionar</a>';
                        ?></td>
                </tr>
                <?php
            };
            ?>
            </tbody>
        </table>
    </div>
    <div class="col-md-12 col-sm-12 col-xs-12" style="text-align: center; width: 400px; margin: 0 auto;">
        <nav>
            <ul class="pagination2">
                <?php if (!empty($total_pages)):for ($i = 1; $i <= $total_pages; $i++):
                    if ($i == 1):?>
                        <li class='active' id="<?php echo $i; ?>"><a href='pagination.php?page=<?php echo $i; ?>'><?php echo $i; ?></a></li>
                    <?php else: ?>
                        <li id="<?php echo $i; ?>"><a href='pagination.php?page=<?php echo $i; ?>'><?php echo $i; ?></a>
                        </li>
                    <?php endif; ?>
                <?php endfor;endif; ?>
            </ul>
        </nav>
    </div>
</div>
</body>

<script type="text/javascript">
    $(document).ready(function () {
        var cd = document.getElementById("cd");

        $('.pagination2').pagination2({
            items: <?php echo $total_records;?>,
            itemsOnPage: <?php echo $limit;?>,
            cssStyle: 'compact-theme',
            currentPage: 1,
            onPageClick: function (pageNumber) {
                var campo = jQuery("#target-content");
                campo.html('carregando...');
                campo.load("pagination/pagination.php?page=" + pageNumber,{'a': cd.value,'page': pageNumber});
            }
        });
    });
</script>

 

Quando executado mostra o seguinte:

mFmRzSQwRUCvq5lf6-H0eA.png

Eu consigo introduzir e remover os participantes da atividade, agora quando vou para as outras páginas ele introduz o participantes mas volta para a página numero 1 e não muda o numero da página na numeração. O que pretendia era que ele ao introduzir o participante se mantivesse na mesma página.

Código de quando introduz o participante:

Spoiler

<?php
function mysqli_result($result , $offset , $field = 0){
    $result->data_seek($offset);
    $row = $result->fetch_array();
    return $row[$field];
}
session_start();
require("C:/xampp/htdocs/connect.php");

/*Teste-inicio*/
$limit = 10;
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
//echo "start: ",$start_from,"<br> page: ",$page,"<br>limit:",$limit,"<br>";

$sql = "SELECT cd_p, nome, morada FROM participantes ORDER BY cd_p ASC LIMIT $start_from, $limit";
//echo $sql;
$rs_result = mysqli_query($connect, $sql);

/*Teste-fim*/

$p = $_REQUEST['p'];
$cd = $_REQUEST['a'];
$sql = "INSERT INTO participantes_atividades (cd_p,cd_ati) VALUES ('$p','$cd')";

if (mysqli_query($connect, $sql) or die (mysqli_error($connect))) {
    $output = '';
    $select_query = "SELECT cd_p, nome, morada FROM participantes ORDER BY cd_p";
    $result = mysqli_query($connect, $select_query) or die("ERRO: Inserção na Tabela participantes_atividades");
    $output .= '
        <table class="table table-bordered table-striped">
            <thead>
            <tr>
                <th width="5%">#</th>
                <th width="50%">Nome</th>
                <th width="35%">Morada</th>
                <th width="10%">Estado</th>
            </tr>
            </thead>
            <tbody id="target-content">
    ';
    while ($row = mysqli_fetch_array($rs_result)) {
        $pt = $row['cd_p'];
        $query2 = "SELECT participantes.cd_p, participantes_atividades.cd_ati FROM participantes_atividades, participantes WHERE participantes.cd_p = participantes_atividades.cd_p AND participantes_atividades.cd_ati = $cd AND participantes_atividades.cd_p = $pt ORDER BY cd_p";
        $result2 = mysqli_query($connect, $query2) or die ("ERRO: Ligação à  Tabela participantes_atividades");

        $output .= '
        <tr class="table-search">
            <td>' . $row["cd_p"] . '</td>
            <td>' . $row["nome"] . '</td>
            <td>' . $row["morada"] . '</td>
            <td>';
        if ($row2 = mysqli_fetch_array($result2)) {
            $output .= '<a data-id=' . $row['cd_p'] . ' name="bRemover" class="btn btn-danger btn-xs bRemover-data">Remover</a>';
        } else {
            $output .= '<a data-id=' . $row["cd_p"] . '  name="bAdicionar" class="btn btn-primary btn-xs bAdicionar-data">Adicionar</a>';
        }
        $output .= '
            </td>
        </tr>
        ';
    }
    $output .= '
            </tbody>
        </table>';
    echo $output;
    $nome_par = mysqli_result(mysqli_query($connect,"SELECT nome FROM participantes WHERE cd_p = '$p' LIMIT 1"), 0); //Indica qual o participante
    $nome_ati = mysqli_result(mysqli_query($connect,"SELECT nome_ati FROM atividades WHERE cd_ati = '$cd' LIMIT 1"), 0); //Indica qual a atividade
    $cuti = $_SESSION['cduser'];
    $uti = $_SESSION['user'];
    $log = "INSERT INTO logs (cd_uti, acao, cd_tp_log) VALUES ('$cuti', 'Inseriu o participante: \"$nome_par\" na atividade \"$nome_ati\".','4')";
    mysqli_query($connect, $log);
}

 

simplePagination.js:

Spoiler

/**
* simplePagination.js v1.6
* A simple jQuery pagination plugin.
* http://flaviusmatis.github.com/simplePagination.js/
*
* Copyright 2012, Flavius Matis
* Released under the MIT license.
* http://flaviusmatis.github.com/license.html
*/

(function($){

	var methods = {
		init: function(options) {
			var o = $.extend({
				items: 1,
				itemsOnPage: 1,
				pages: 0,
				displayedPages: 5,
				edges: 1,
				currentPage: 0,
				hrefTextPrefix: '#page-',
				hrefTextSuffix: '',
				prevText: 'Anterior',
				nextText: 'Seguinte',
				ellipseText: '&hellip;',
				cssStyle: 'dark-theme',
				listStyle: '',
				labelMap: [],
				selectOnClick: true,
				nextAtFront: false,
				invertPageOrder: false,
				useStartEdge : true,
				useEndEdge : true,
				onPageClick: function(pageNumber, event) {
					alert("teste");
					// Callback triggered when a page is clicked
					// Page number is given as an optional parameter
				},
				onInit: function() {
					// Callback triggered immediately after initialization
				}
			}, options || {});

			var self = this;

			o.pages = o.pages ? o.pages : Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
			if (o.currentPage)
				o.currentPage = o.currentPage - 1;
			else
				o.currentPage = !o.invertPageOrder ? 0 : o.pages - 1;
			o.halfDisplayed = o.displayedPages / 2;

			this.each(function() {
				self.addClass(o.cssStyle + ' simple-pagination2').data('pagination2', o);
				methods._draw.call(self);
			});

			o.onInit();

			return this;
		},

		selectPage: function(page) {
			methods._selectPage.call(this, page - 1);
			return this;
		},

		prevPage: function() {
			var o = this.data('pagination2');
			if (!o.invertPageOrder) {
				if (o.currentPage > 0) {
					methods._selectPage.call(this, o.currentPage - 1);
				}
			} else {
				if (o.currentPage < o.pages - 1) {
					methods._selectPage.call(this, o.currentPage + 1);
				}
			}
			return this;
		},

		nextPage: function() {
			var o = this.data('pagination2');
			if (!o.invertPageOrder) {
				if (o.currentPage < o.pages - 1) {
					methods._selectPage.call(this, o.currentPage + 1);
				}
			} else {
				if (o.currentPage > 0) {
					methods._selectPage.call(this, o.currentPage - 1);
				}
			}
			return this;
		},

		getPagesCount: function() {
			return this.data('pagination2').pages;
		},

		setPagesCount: function(count) {
			this.data('pagination2').pages = count;
		},

		getCurrentPage: function () {
			return this.data('pagination2').currentPage + 1;
		},

		destroy: function(){
			this.empty();
			return this;
		},

		drawPage: function (page) {
			var o = this.data('pagination2');
			o.currentPage = page - 1;
			this.data('pagination2', o);
			methods._draw.call(this);
			return this;
		},

		redraw: function(){
			methods._draw.call(this);
			return this;
		},

		disable: function(){
			var o = this.data('pagination2');
			o.disabled = true;
			this.data('pagination2', o);
			methods._draw.call(this);
			return this;
		},

		enable: function(){
			var o = this.data('pagination2');
			o.disabled = false;
			this.data('pagination2', o);
			methods._draw.call(this);
			return this;
		},

		updateItems: function (newItems) {
			var o = this.data('pagination2');
			o.items = newItems;
			o.pages = methods._getPages(o);
			this.data('pagination2', o);
			methods._draw.call(this);
		},

		updateItemsOnPage: function (itemsOnPage) {
			var o = this.data('pagination2');
			o.itemsOnPage = itemsOnPage;
			o.pages = methods._getPages(o);
			this.data('pagination2', o);
			methods._selectPage.call(this, 0);
			return this;
		},

		getItemsOnPage: function() {
			return this.data('pagination2').itemsOnPage;
		},

		_draw: function() {
			var	o = this.data('pagination2'),
				interval = methods._getInterval(o),
				i,
				tagName;

			methods.destroy.call(this);
			
			tagName = (typeof this.prop === 'function') ? this.prop('tagName') : this.attr('tagName');

			var $panel = tagName === 'UL' ? this : $('<ul' + (o.listStyle ? ' class="' + o.listStyle + '"' : '') + '></ul>').appendTo(this);

			// Generate Prev link
			if (o.prevText) {
				methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage - 1 : o.currentPage + 1, {text: o.prevText, classes: 'prev'});
			}

			// Generate Next link (if option set for at front)
			if (o.nextText && o.nextAtFront) {
				methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage + 1 : o.currentPage - 1, {text: o.nextText, classes: 'next'});
			}

			// Generate start edges
			if (!o.invertPageOrder) {
				if (interval.start > 0 && o.edges > 0) {
					if(o.useStartEdge) {
						var end = Math.min(o.edges, interval.start);
						for (i = 0; i < end; i++) {
							methods._appendItem.call(this, i);
						}
					}
					if (o.edges < interval.start && (interval.start - o.edges != 1)) {
						$panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
					} else if (interval.start - o.edges == 1) {
						methods._appendItem.call(this, o.edges);
					}
				}
			} else {
				if (interval.end < o.pages && o.edges > 0) {
					if(o.useStartEdge) {
						var begin = Math.max(o.pages - o.edges, interval.end);
						for (i = o.pages - 1; i >= begin; i--) {
							methods._appendItem.call(this, i);
						}
					}

					if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
						$panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
					} else if (o.pages - o.edges - interval.end == 1) {
						methods._appendItem.call(this, interval.end);
					}
				}
			}

			// Generate interval links
			if (!o.invertPageOrder) {
				for (i = interval.start; i < interval.end; i++) {
					methods._appendItem.call(this, i);
				}
			} else {
				for (i = interval.end - 1; i >= interval.start; i--) {
					methods._appendItem.call(this, i);
				}
			}

			// Generate end edges
			if (!o.invertPageOrder) {
				if (interval.end < o.pages && o.edges > 0) {
					if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
						$panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
					} else if (o.pages - o.edges - interval.end == 1) {
						methods._appendItem.call(this, interval.end);
					}
					if(o.useEndEdge) {
						var begin = Math.max(o.pages - o.edges, interval.end);
						for (i = begin; i < o.pages; i++) {
							methods._appendItem.call(this, i);
						}
					}
				}
			} else {
				if (interval.start > 0 && o.edges > 0) {
					if (o.edges < interval.start && (interval.start - o.edges != 1)) {
						$panel.append('<li class="disabled"><span class="ellipse">' + o.ellipseText + '</span></li>');
					} else if (interval.start - o.edges == 1) {
						methods._appendItem.call(this, o.edges);
					}

					if(o.useEndEdge) {
						var end = Math.min(o.edges, interval.start);
						for (i = end - 1; i >= 0; i--) {
							methods._appendItem.call(this, i);
						}
					}
				}
			}

			// Generate Next link (unless option is set for at front)
			if (o.nextText && !o.nextAtFront) {
				methods._appendItem.call(this, !o.invertPageOrder ? o.currentPage + 1 : o.currentPage - 1, {text: o.nextText, classes: 'next'});
			}
		},

		_getPages: function(o) {
			var pages = Math.ceil(o.items / o.itemsOnPage);
			return pages || 1;
		},

		_getInterval: function(o) {
			return {
				start: Math.ceil(o.currentPage > o.halfDisplayed ? Math.max(Math.min(o.currentPage - o.halfDisplayed, (o.pages - o.displayedPages)), 0) : 0),
				end: Math.ceil(o.currentPage > o.halfDisplayed ? Math.min(o.currentPage + o.halfDisplayed, o.pages) : Math.min(o.displayedPages, o.pages))
			};
		},

		_appendItem: function(pageIndex, opts) {
			var self = this, options, $link, o = self.data('pagination2'), $linkWrapper = $('<li></li>'), $ul = self.find('ul');

			pageIndex = pageIndex < 0 ? 0 : (pageIndex < o.pages ? pageIndex : o.pages - 1);

			options = {
				text: pageIndex + 1,
				classes: ''
			};

			if (o.labelMap.length && o.labelMap[pageIndex]) {
				options.text = o.labelMap[pageIndex];
			}

			options = $.extend(options, opts || {});

			if (pageIndex == o.currentPage || o.disabled) {
				if (o.disabled || options.classes === 'prev' || options.classes === 'next') {
					$linkWrapper.addClass('disabled');
				} else {
					$linkWrapper.addClass('active');
				}
				$link = $('<span class="current">' + (options.text) + '</span>');
			} else {
				$link = $('<a href="' + o.hrefTextPrefix + (pageIndex + 1) + o.hrefTextSuffix + '" class="page-link">' + (options.text) + '</a>');
				$link.click(function(event){
					return methods._selectPage.call(self, pageIndex, event);
				});
			}

			if (options.classes) {
				$link.addClass(options.classes);
			}

			$linkWrapper.append($link);

			if ($ul.length) {
				$ul.append($linkWrapper);
			} else {
				self.append($linkWrapper);
			}
		},

		_selectPage: function(pageIndex, event) {
			var o = this.data('pagination2');
			o.currentPage = pageIndex;
			if (o.selectOnClick) {
				methods._draw.call(this);
			}
			return o.onPageClick(pageIndex + 1, event);
		}

	};

	$.fn.pagination2 = function(method) {

		// Method calling logic
		if (methods[method] && method.charAt(0) != '_') {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.pagination');
		}

	};

})(jQuery);

 

Algumas sugestões?

 

Cumprimentos,

Fábio Peixeiro

Share this post


Link to post
Share on other sites
HappyHippyHippo

a edição dos participante não é realizada sobre uma "modal window" ? se sim, porque razão existe o redirecionament o para outra páigna ?


IRC : sim, é algo que ainda existe >> #p@p

Share this post


Link to post
Share on other sites
Fábio Peixeiro

Isso, a edição dos participantes é realizada numa modal, eu consigo mudar de páginas dentro do modal. O meu problema é que quando insiro um participante quando ele vai a dar refresh com o ajax ele muda a data que é mostrada para a data da primeira página mesmo que me encontre noutro numero página, o que queria é que ao mudar a data se mantivesse no mesmo numero de página.

Share this post


Link to post
Share on other sites
HappyHippyHippo

e porque está a mudar a data da primeira página ? como está a fazer isso ?


IRC : sim, é algo que ainda existe >> #p@p

Share this post


Link to post
Share on other sites
Fábio Peixeiro

Eu procurei por um script e tentei adaptar ao que pretendia, o problema foi mesmo não conseguir adaptar :/

Share this post


Link to post
Share on other sites
Fábio Peixeiro

Já consegui fazer algumas alterações bem sucedidas:

- Consigo adicionar/remover o participante e manter-me na mesma página;

- Consigo Procurar pelo nome e adicionar/remover mantendo-se na mesma página.

O problema é que após adicionar/remover o participante a paginação deixa de funcionar.

 

Contéudo que é carregado ao abrir a modal:

Spoiler

<?php
$c = $_REQUEST['a'];
require("C:/xampp/htdocs/connect.php");
//for total count data
$countSql = "SELECT COUNT(cd_p) FROM participantes";
$tot_result = mysqli_query($connect, $countSql);
$row = mysqli_fetch_row($tot_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);

//for first time load data
if (isset($_GET["page"])) {
    $page = $_GET["page"];
} 
else {
    $page = 1;
}
$start_from = ($page - 1) * $limit;
$sql = "SELECT cd_p, nome, morada FROM participantes ORDER BY cd_p ASC LIMIT $start_from, $limit";
$rs_result = mysqli_query($connect, $sql);
?>
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
    <script src="part_ati/css/jquery.simplePagination.js"></script>
    <link href="part_ati/css/simplePagination.css" rel="stylesheet">
    <script src="part_ati/js/script.js"></script>
    <script src="part_ati/js/ajax.js"></script>
</head>
<body>
<div class="container">
    <div class="table-responsive">
        <input type="hidden" name="cd" id="cd" value="<?php echo $c; ?>">
        <div id="partTable">
            <div align="center">
                <p>
                    <input type="text" name="search" id="search" class="form-control" style="max-width: 200px; text-align: center" placeholder="Procurar por nome" onkeyup="return search_table(this, <?php echo $c;?>);">
                </p>
            </div>
            <div id="searchOutput" style=" overflow: auto">
                <input type="hidden" name="pg" id="pg" value="<?php echo $page; ?>">
                <table id="tabela-modal" class="table table-striped table-bordered" cellspacing="0" width="100%">
                    <thead>
                    <tr>
                        <th width="5%">#</th>
                        <th width="50%">Nome</th>
                        <th width="35%">Morada</th>
                        <th width="10%">Estado</th>
                    </tr>
                    </thead>
                    <tbody id="target-content">
                    <?php
                    while ($row = mysqli_fetch_array($rs_result)) {
                        $p = $row['cd_p'];
                        $query2 = "SELECT participantes.cd_p, participantes_atividades.cd_ati FROM participantes_atividades, participantes WHERE participantes.cd_p = participantes_atividades.cd_p AND participantes_atividades.cd_ati = $c AND participantes_atividades.cd_p = $p ORDER BY cd_p";
                        $result2 = mysqli_query($connect, $query2) or die ("Erro");
                        ?>
                        <tr class="table-search">
                            <td><?php echo $row["cd_p"]; ?></td>
                            <td><?php echo $row["nome"]; ?></td>
                            <td><?php echo $row["morada"]; ?></td>
                            <td><?php
                                if ($row2 = mysqli_fetch_array($result2))
                                    echo '<a data-id=', $row['cd_p'], ' name="bRemover" class="btn btn-danger btn-xs bRemover-data" >Remover</a>';
                                else echo '<a data-id=', $row['cd_p'], ' name="bAdicionar" class="btn btn-primary btn-xs bAdicionar-data" >Adicionar</a>';
                                ?></td>
                        </tr>
                        <?php
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="col-md-12 col-sm-12 col-xs-12" style="text-align: center; width: 400px; margin: 0 auto;">
            <nav>
                <ul class="pagination2">
                    <?php if (!empty($total_pages)):for ($i = 1; $i <= $total_pages; $i++):
                        if ($i == 1):?>
                            <li class='active' id="<?php echo $i; ?>"><a href='part_ati/pagination.php?page=<?php echo $i; ?>'><?php echo $i; ?></a></li>
                        <?php else: ?>
                            <li id="<?php echo $i; ?>"><a href='part_ati/pagination.php?page=<?php echo $i; ?>'><?php echo $i; ?></a>
                            </li>
                        <?php endif; ?>
                    <?php endfor;endif; ?>
                </ul>
            </nav>
        </div>
    </div>
</div>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function () {
        var cd = document.getElementById("cd");

        $('.pagination2').pagination2({
            items: <?php echo $total_records;?>,
            itemsOnPage: <?php echo $limit;?>,
            cssStyle: 'compact-theme',
            currentPage: 1,
            onPageClick: function (pageNumber) {
                document.getElementById("pg").value = pageNumber;
                var campo = jQuery("#target-content");
                campo.html('carregando...');
                campo.load("part_ati/pagination.php?pg=" + pageNumber, {'a': cd.value});
            }
        });
    });
</script>

 

Ajax que faz inserir e procurar sem page refresh:

Script.js

Spoiler

$(document).ready(function () {

    $(document).on('click', '.bAdicionar-data', function () {
        var id = $(this).attr('data-id');
        var ati = document.getElementById("ati");
        var pg = document.getElementById("pg");
        var search = document.getElementById("search");
        $.ajax({
            url: "part_ati/js/ins.php",
            method: "POST",
            data: {p: id, a: ati.value, search:search.value, 'pg': pg.value},
            success: function (data) {
                var s = $("#search").val;

                if(s !== null){
                    $("#search").val("");
                }
                $('#partTable').html(data);
            }
        });
    });

    $(document).on('click', '.bRemover-data', function () {
        var id = $(this).attr('data-id');
        var ati = document.getElementById("ati");
        var pg = document.getElementById("pg");
        var search = document.getElementById("search");
        $.ajax({
            url: "part_ati/js/del.php",
            method: "POST",
            data: {p: id, a: ati.value, search:search.value, 'pg': pg.value},
            success: function (data) {
                var s = $("#search").val;

                if(s !== null){
                    $("#search").val("");
                }
                $('#partTable').html(data);
            }
        });
    });
});

 

Ajax.js

Spoiler

function search_table(e, ati) {// função de ajax
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else  {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState===4 && xmlhttp.status===200) {
            document.getElementById("searchOutput").style.display="block";
            document.getElementById("searchOutput").innerHTML = xmlhttp.responseText;
        }
    }
    var ati = document.getElementById("ati").value;
    xmlhttp.open("GET","part_ati/js/search.php?search="+e.value+"&ati="+ati,true);
    xmlhttp.send();
}

 

Ficheiro PHP que adiciona:
 

Spoiler

<?php
function mysqli_result($result , $offset , $field = 0){
    $result->data_seek($offset);
    $row = $result->fetch_array();
    return $row[$field];
}
session_start();
require("C:/xampp/htdocs/connect.php");
$p = $_REQUEST['p'];
$cd = $_REQUEST['a'];
$s = $_REQUEST['search'];

/*Teste-inicio*/
if (isset($_REQUEST["pg"])) { $page  = $_REQUEST["pg"]; } else { $page=1; };
$start_from = ($page-1) * $limit;
/*echo "start: ",$start_from,"<br> page: ",$page,"<br>limit:",$limit,"<br>";*/
if(isset($s)){
    $sql = "SELECT cd_p, nome, morada FROM participantes WHERE nome LIKE '%$s%' ORDER BY cd_p ASC LIMIT $start_from, $limit";
}
else {
    $sql = "SELECT cd_p, nome, morada FROM participantes ORDER BY cd_p ASC LIMIT $start_from, $limit";
}
//echo $sql;
$rs_result = mysqli_query($connect, $sql) or die("ERRO: Inserção na Tabela participantes_atividades");
/*Teste-fim*/

$query = "INSERT INTO participantes_atividades (cd_p,cd_ati) VALUES ('$p','$cd')";

if (mysqli_query($connect, $query) or die (mysqli_error($connect))) {
    $output = '';
    $output .= '
    <div id="partTable">
        <div align="center">
            <p>
                <input value="' . $s . '" type="text" name="search" id="search" class="form-control" style="max-width: 200px; text-align: center" placeholder="Procurar por nome" onkeyup="return search_table(this, ' . $cd . ');">
            </p>
        </div>
        <div id="searchOutput" style=" overflow: auto">
            <input type="hidden" name="pg" id="pg" value="' . $page . '">
            <table id="tabela-modal" class="table table-striped table-bordered" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th width="5%">#</th>
                        <th width="50%">Nome</th>
                        <th width="35%">Morada</th>
                        <th width="10%">Estado</th>
                    </tr>
                </thead>
    ';
    while ($row = mysqli_fetch_array($rs_result)) {
        $pt = $row['cd_p'];
        $query2 = "SELECT participantes.cd_p, participantes_atividades.cd_ati FROM participantes_atividades, participantes WHERE participantes.cd_p = participantes_atividades.cd_p AND participantes_atividades.cd_ati = $cd AND participantes_atividades.cd_p = $pt ORDER BY cd_p";
        $result2 = mysqli_query($connect, $query2) or die ("ERRO: Ligação à  Tabela participantes_atividades");

        $output .= '
        <tr class="table-search">
            <td>' . $row["cd_p"] . '</td>
            <td>' . $row["nome"] . '</td>
            <td>' . $row["morada"] . '</td>
            <td>';
        if ($row2 = mysqli_fetch_array($result2)) {
            $output .= '<a data-id=' . $row['cd_p'] . ' name="bRemover" class="btn btn-danger btn-xs bRemover-data">Remover</a>';
        } else {
            $output .= '<a data-id=' . $row["cd_p"] . '  name="bAdicionar" class="btn btn-primary btn-xs bAdicionar-data">Adicionar</a>';
        }
        $output .= '
            </td>
        </tr>
        ';
    }
    $output .= '
            </table>
        </div>
    </div>';

    echo $output;
    $nome_par = mysqli_result(mysqli_query($connect,"SELECT nome FROM participantes WHERE cd_p = '$p' LIMIT 1"), 0); //Indica qual o participante
    $nome_ati = mysqli_result(mysqli_query($connect,"SELECT nome_ati FROM atividades WHERE cd_ati = '$cd' LIMIT 1"), 0); //Indica qual a atividade
    $cuti = $_SESSION['cduser'];
    $uti = $_SESSION['user'];
    $log = "INSERT INTO logs (cd_uti, acao, cd_tp_log) VALUES ('$cuti', 'Inseriu o participante: \"$nome_par\" na atividade \"$nome_ati\".','4')";
    mysqli_query($connect, $log);
}

 

Ficheiro PHP que procura:
 

Spoiler

<?php
require("C:/xampp/htdocs/connect.php");
$s = $_GET["search"];    // recebe uma parâmetro por GET
$a = $_GET["ati"];    // recebe uma parâmetro por GET
$output = '';
//echo "search: ",$s,"<br>";
/*Teste-inicio*/
$page = 1;
$start_from = ($page-1) * $limit;

if (isset($s)) {
    $sql = "SELECT cd_p, nome, morada FROM participantes WHERE nome LIKE '%$s%' ORDER BY cd_p ASC LIMIT $start_from, $limit";
}
else {
    $sql = "SELECT cd_p, nome, morada FROM participantes ORDER BY cd_p ASC LIMIT $start_from, $limit";
}

/*echo "start: ",$start_from,"<br> page: ",$page,"<br>limit:",$limit,"<br>";*/
//echo $sql;
$rs_result = mysqli_query($connect, $sql)or die (mysqli_error($connect));
/*Teste-fim*/

    if(mysqli_num_rows($rs_result) == 0)
        $output .= '
    <div class="col-md-12 col-sm-12 col-xs-12" style="text-align: center">
            <span> Não foram encontrados resultados. </span>
    </div>
        ';
    else {
        $output .= '
            <input type="hidden" name="pg" id="pg" value="' . $page . '">
            <table id="tabela-modal" class="table table-striped table-bordered" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th width="5%">#</th>
                        <th width="50%">Nome</th>
                        <th width="35%">Morada</th>
                        <th width="10%">Estado</th>
                    </tr>
                </thead>
                <tbody>
            ';
        while ($row = mysqli_fetch_array($rs_result)) {
            $p = $row['cd_p'];
            $query2 = "SELECT participantes.cd_p, participantes_atividades.cd_ati FROM participantes_atividades participantes_atividades, participantes participantes WHERE participantes.cd_p = participantes_atividades.cd_p AND participantes_atividades.cd_ati = $a AND participantes_atividades.cd_p = $p ORDER BY cd_p";
            $result2 = mysqli_query($connect, $query2) or die (mysqli_error($connect));
            $output .= '
                    <tr class="table-search">
                        <td>'; $output .= $row["cd_p"]; $output .= '</td>
                        <td>'; $output .= $row["nome"]; $output .= '</td>
                        <td>'; $output .= $row["morada"]; $output .= '</td>
                        <td>';
            if ($row2 = mysqli_fetch_array($result2))
                $output .= '<a data-id=' . $row['cd_p'] . ' name="bRemover" class="btn btn-danger btn-xs bRemover-data" >Remover</a>';
            else $output .= '<a data-id=' . $row['cd_p'] . ' name="bAdicionar" class="btn btn-primary btn-xs bAdicionar-data" >Adicionar</a>';
                        $output .= '
                        </td>
                    </tr>
    ';
        }
    }
    $output .= '
        </tbody>
    </table>
';

echo $output;

 

@HappyHippyHippo será que me podias ajudar por TeamViewer outra vez se possivel?

 

EDIT: Erro corrigido, quando eu atualizava a DIV partTable nao estava a introduzir o TBODY com o ID="target-content", dai a paginação não estar a funcionar, Agora o Problema é quando procuro por um certo nome de participante o numero de páginas atualiza mas perde o javascript e o css.

Edited by Fábio Peixeiro

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.