In general, I made a paginal output that worked successfully with all the sampling conditions (you can select a filter in the form, sort, date, and output everything as needed), but when I decided to do everything through ajax, I had difficulty with that Data occurs only after pressing the button, then the whole selection appears (10 records per page) and the page-by-page navigation along with the selection. On ajax, the sample is displayed using json and everything works, but how to display the function that displays page-by-page navigation I won’t attach my mind. Here is the js code:

$("#sortfilt").submit(function(e) { event.preventDefault(); var showusers = 'showusers'; var sort = $('#sort').val(); var filtgroup = $('#filtgroup').val(); var datefrom = $('#datefrom').val(); var dateto = $('#dateto').val(); $.get("ajax.php", {showusers: showusers, sort: sort, filtgroup: filtgroup, datefrom: datefrom, dateto: dateto}, function (data) { alert(data); data = JSON.parse(data); alert(data); $('#users').empty(); for(var key in data) { var obj = (key, data[key]); $('#users').append("<ul><li><img src=" + obj.imageExtention + "></li><li>" + obj.login + "</li> <li>" + obj.name + "</li> <li>" + obj.email + "</li> <li>" + obj.expirationDateAndTime + "</li> <li><button name='delete' value='" + obj.consumerId + "'>Удалить</button></li></ul>"); } }); }); 

and here is ajax.php:

 if(isset($_GET['showusers'])) { $data = array(); if($_GET['sort']) { $sort = $db->escape($_GET['sort']); $order = " ORDER BY $sort ASC";//формируем запрос } if($_GET['filtgroup'] === 'all') { $filter = ""; } else { $filt = $db->escape($_GET['filtgroup']); $filter = "AND consumer.groupId = '$filt'";//формируем запрос } if($_GET['datefrom'] && $_GET['dateto']) { $from = $db->escape($_GET['datefrom']); $to = $db->escape($_GET['dateto']); $datequery = "AND consumer.expirationDateAndTime BETWEEN '$from' AND '$to'";//добавляем продолжнение запроса на дату, если она введена } else { $datequery = ""; } // Подготовка к постраничному выводу $perpage = 10; // Количество отображаемых данных из БД if (empty(@$_GET['page']) || ($_GET['page'] <= 0)) { $page = 1; } else { $page = (int) $_GET['page']; // Считывание текущей страницы } // Общее количество информации $count = mysqli_num_rows($db->query('SELECT * FROM `consumer`')) or die('error! Записей не найдено!'); $pages_count = ceil($count / $perpage); // Количество страниц // Если номер страницы оказался больше количества страниц if ($page > $pages_count) { $page = $pages_count; } $start_pos = ($page - 1) * $perpage; // Начальная позиция, для запроса к БД //$boom = Reg::linkbar($page, $pages_count); function linkbar($page, $pages_count) { for ($j = 1; $j <= $pages_count; $j++) { // Вывод ссылки if ($j == $page) { echo ' <a style="color: #808000;" >'.$j.'</a> '; } else { echo ' <a style="color: #808000;" href='.$_SERVER['php_self'].'?page='.$j.'&showusers>'.$j.'</a> ';//возможно после showusers нужно добавить ='.$j.' } // Выводим разделитель после ссылки, кроме последней // например, вставить "|" между ссылками if ($j != $pages_count) { echo ' | '; } } return true; } //Выводим запрос $res = $db->query("SELECT * FROM `consumer`, `group` WHERE consumer.groupId = group.groupId $filter $datequery $order LIMIT ".$start_pos.", ".$perpage);//$filter $datequery $order //var_dump($res); while(($row = $db->fetch_assoc($res)) != false) { $data[] = $row; } echo json_encode($data); } 

Also in this file is the linkbar () function, which displays the navigation and I do not understand how to grasp this function, that the navigation was output along with the selection

  • 2
    The first thing that caught my eye: in the first line, the argument e passed to the function, and the second is the event . Is this what the event exists somewhere higher? - Mr. Brightside
  • Yes, it works, cancels the default action, and so it is conceived - myfavoritename

2 answers 2

If algorithmically. At a minimum, AJAX should transmit the number of the current page page in the request - then the server will generate the answer for the "desired" page. To draw a paging, you need to make a separate function (analog linkbar ()) on the client, which is called in the body of success from AJAX. When you click on the page of paging, you need to call AJAX with the corresponding click of page and, by success, mark the active page in the page. In an amicable way, the server in response should give the total number of lines and the page number it gave, so that it is more convenient to draw a paging block on the client.

  • For example, in the function after the cycle, specify the function page () and then function page () {$ .ajax ({type: "GET", url: "index.php", success: function () {// ..... }}); } did I understand you correctly? If so, how can I write a function like linkbar () in jquery? - myfavoritename

Here is an example of my code for dynamic content download. This code works with loading photos from a specific album:

  _prototype.getPhotosFromAlbum = function (album_id, page) { var imageBlock = '<div class="col s12 m3" style="text-align: center">' + '<div class="card-panel white">' + '<img src="{0}" alt="">' + '</div>' + '</div>'; $.get('/api/albums/' + album_id + '/photos/' + page, function (response) { if (page == 1) { $('div.album-photos').empty(); } if (response.photos.length > 0) { $.each(response.photos, function (i, photo) { $('div.album-photos').append(imageBlock.replace('{0}', photo.url)); }); } if (response.photos.length == 8) { $('div.album-photos').append('<div class="row"><div style="text-align: center">' + '<button class="btn btn-primary load-more-photos" data-album-id="' + album_id + '" data-page="' + (page + 1) + '">' + 'Завантажити більше фото' + '</button>' + '</div>' + '</div>'); $('button.load-more-photos').on('click', function () { _prototype.getPhotosFromAlbum($(this).data('album-id'), $(this).data('page')); $(this).remove(); }); } }); };