У меня есть таблица с пользователями на основе числовой параметр.
Я встроил фильтр, который прослушивает ввод и делает AJAX-вызов каждый раз с этим фильтром на имя. Как построение таблицы содержит строки с пользователями и устанавливает нумерацию страниц ВЫШЕ весь стол.
Когда я заполняю tbody ответом на вызов AJAX, он устанавливает нумерацию страниц В стол..
Как это можно решить? Функция фильтра работает отлично, это просто нумерация страниц, которая не хочет.
Оригинальная страница
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name</th>
<th>Bank</th>
<th>IBAN</th>
</tr>
</thead>
<tbody>
<?php
try {
//Find out how many items are in the table
$total = $pdo->query('SELECT COUNT(*) FROM tatble1 WHERE nr = ' . $nr)->fetchColumn();
if($total > 0){
//Setting Limit, Offset, End, Total and prepared Query
...
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
// Display the results
foreach ($stmt as $row) {
echo
'<tr data-zp-id=' . $row["id"] . '>
<td>' . $row["name"] . '</td>
<td>' . $row["bank"] . '</td>
<td>' . $row["iban"] . '</td>
</tr>';
}
echo '<div id="pagination">';
// The "back" link
$prevlink = ($page > 1) ?
'<a href="?'.$cutUrl.'&page=1" title="Erste Seite"><button class="faecher">«</button></a> <a href="?'.$cutUrl.'&page=' . ($page - 1) . '" title="Vorherige Seite"><button class="faecher">‹</button></a>' :
'<button class="faecher" id="fehlt">«</button> <button class="faecher" id="fehlt">‹</button>';
// The "forward" link
$nextlink = ($page < $pages) ?
'<a href="?'.$cutUrl.'&page=' . ($page + 1) . '" title="Nächste Seite"><button class="faecher">›</button></a> <a href="?'.$cutUrl.'&page=' . $pages . '" title="Letzte Seite"><button class="faecher">»</button></a>' :
'<button class="faecher" id="fehlt">›</button> <button class="faecher" id="fehlt">»</button>';
// Display the paging information
echo '<div id="paging">
<p>', $prevlink, ' Seite ', $page, ' von ', $pages, ' | Zeige ', $start, ' - ', $end, ' von ', $total, ' Ergebnissen ', $nextlink, ' </p>
</div>
</div>';
}
} else {
echo '<h2>Keine Personen gefunden!</h2>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
?>
</tbody>
</table><br/><br/>
<input type="text" id="filter" value=""/>
Как это выглядит:
Функция фильтра
$('#filter').on( 'input' , function(){
var filter_input = $(this).val();
$.ajax({
url : 'ajax4.php',
type : 'POST',
data : {
fil : filter_input
}
})
.done (function(response) { console.log("Response : \n" + response); $('tbody').html(response); })
.fail (function(jqXHR, textStatus, errorThrown ) { alert('[ui-state-error ' + jqXHR.status + "] " + textStatus + " : " + errorThrown); });
//Reset
if(filter_input == "" || filter_input.length < 1){
window.location.reload(true);
}
});
AJAX Call
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
session_start();
include "../connect.php";
(int) $nr = $_SESSION["nr"];
(string) $filter = $_POST["fil"];
try {
//Find out how many items are in the table
$total = $pdo->query('SELECT COUNT(*) table1 WHERE nr = ' . $nr . ' AND name LIKE "%' . $filter . '%"')->fetchColumn();
if($total > 0){
//Setting Limit, Offset, End, Total and prepared Query
...
// Prepare the paged query
...
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
echo '<div id="pagination">';
// The "back" link
$prevlink = ($page > 1) ? '<a href="?'.$cutUrl.'&page=1" title="Erste Seite"><button class="faecher">«</button></a> <a href="?'.$cutUrl.'&page=' . ($page - 1) . '" title="Vorherige Seite"><button class="faecher">‹</button></a>' : '<button class="faecher" id="fehlt">«</button> <button class="faecher" id="fehlt">‹</button>';
// The "forward" link
$nextlink = ($page < $pages) ? '<a href="?'.$cutUrl.'&page=' . ($page + 1) . '" title="Nächste Seite"><button class="faecher">›</button></a> <a href="?'.$cutUrl.'&page=' . $pages . '" title="Letzte Seite"><button class="faecher">»</button></a>' : '<button class="faecher" id="fehlt">›</button> <button class="faecher" id="fehlt">»</button>';
// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Seite ', $page, ' von ', $pages, ' | Zeige ', $start, ' - ', $end, ' von ', $total, ' Ergebnissen ', $nextlink, ' </p></div>
</div>';
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
// Display the results
foreach ($stmt as $row) {
echo
'<tr data-zp-id=' . $row["id"] . '>
<td>' . $row["name"] . '</td>
<td>' . $row["bank"] . '</td>
<td>' . $row["iban"] . '</td>
</tr>';
}
/*tried the pagination code here, didn't get shown or anything happened*/
}
} else {
echo '<h2>Keine Personen gefunden!</h2>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
}
?>
Который выглядит как:
Напишите один PHP-файл, который выведет вашу нумерацию страниц и после полной таблицы, что-то вроде этого:
ajax4.php должен вывести следующее
<div id="your-tables-container">
<div id="pagination">
...
</div>
<table>
<thead>
<tr class="ui-widget-header">
<th>Name</th>
<th>Bank</th>
<th>IBAN</th>
</tr>
</thead>
<tbody>
...
</tbody>
</table>
</div>
Javascript для вызова AJAX должен обновлять всю таблицу, а не только TBODY
Ваш AJAX-вызов должен выглядеть следующим образом:
// also try jQuery.load() method. It makes an AJAX call and automatically replace the innerHtml of the selected DOM-element: http://api.jquery.com/load/
$.ajax({
url : 'ajax4.php',
type : 'POST',
data : {
fil : filter_input
}
}).done(function(response) {
console.log("Response : \n" + response);
$('#your-tables-container').html(response);
}).fail(function(jqXHR, textStatus, errorThrown ) {
alert('[ui-state-error ' + jqXHR.status + "] " + textStatus + " : " + errorThrown);
});
в вашем исходном файле PHP у вас снова такой же / похожий код, нужно ли это?
И в вашем исходном файле PHP вы должны избегать написания кода вашей таблицы дважды. использование require
или, может быть file_get_contents
или что-то типа того:
<?php
require_once('/path/to/ajax4.php');
// or maybe
echo file_get_contents('/path/to/ajax4.php?parameter=if_you_need_it');
?>
Других решений пока нет …