Scroll loading using jquery and PHP
This article explains how to incrementally load items as you scroll down the page. In this example a HTML page is created with an unordered list element where the list items returned by the function gets appended.
HTML Page<div> <ul id="containerName"></ul> <div style="text-align: center;"><img alt="Loading..." src="../assets/images/svg/three-dots.svg" class="loading-info" /></div> <div id="notifyMessage"></div> </div>Jquery
$(document).ready(function () {var offset = 0;var loading = false;$('.loading-info').hide();appendItems(offset, loading);$(window).scroll(function () {if ($('#notifyMessage').html() === "") { if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) { offset += 20; appendItems(offset, loading); } } });});
function appendItems(offset, loading) { if (loading == false) { loading = true; $('.loading-info').show(); $.post('/admin/items/append', { 'offset': offset }, function (data) { loading = false; if (data.trim().length == 0) { $('.loading-info').hide(); $('#notifyMessage').html('<p> End of records</p>'); return; } $('.loading-info').hide(); $("#containerName").append(data); }).fail(function (xhr, ajaxOptions, thrownError) { alert(thrownError); }) } }PHP Function
function append() { $list = NULL; $offset = $_POST['offset']; $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM employees limit $offset, 20"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $list += "<li>id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "</li>"; } } $conn->close(); echo $list; }
No comments:
Post a Comment