Load content on Page scroll with AngularJS and PHP

In infinite page scroll pagination data load dynamically and append at the end of existing content when the user reaches to the bottom while scrolling.

The user doesn’t have to click any button.

I am using ngInfiniteScroll directive for implementing with AngularJS.

With this directive detect page scroll and send AJAX request to get content.

Also, need to include the jQuery library for using it.

In this tutorial, I show how you can load content on page scroll using the ngInfiniteScroll directive in AngularJS.

Load content on Page scroll with AngularJS and PHP


Contents

  1. Table structure
  2. Configuration
  3. Download Plugin
  4. HTML
  5. CSS
  6. PHP
  7. Script
  8. Demo
  9. Conclusion

 


1. Table structure

Create posts table.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Configuration

Create a config.php for database connection.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. Download Plugin

  • Download ngInfiniteScroll plugin from here.
  • Include jQuery, AngularJS, and ng-infinite-scroll.min.js script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="angular.min.js"></script>
<script src="ng-infinite-scroll.min.js"></script>

4. HTML

Included the script.js in the <head>. In this file write AngularJS script.

Add infinite-scroll attribute in the parent container from where you want to detect scrolling.

  • infinite-scroll – Pass method. This is called when reaching the bottom.

Use ng-repeat to read values from the posts Array and add content.

Display the loading message while data is retrieving using <div >. Add ng-show attribute for show and hide it.

Completed Code

<!doctype html>
<html>
  <head>
    <title>Load content on Page scroll with AngularJS and PHP</title> 
    <!-- CSS -->
    <link href='style.css' rel='stylesheet' type='text/css'>

    <!-- Script -->
    <script src="jquery-3.0.0.js"></script>
    <script src="angular.min.js"></script>
    <script src="ng-infinite-scroll.min.js"></script>

    <script src="script.js"></script>

  </head>
  <body ng-app='myapp' ng-controller='fetchCtrl' >
     <div class="container" infinite-scroll="getPosts()" >
 
       <div class="post" ng-repeat='post in posts'>
          <h1 ng-bind='post.title'></h1>
          <p ng-bind='post.shortcontent'></p>
          <a ng-href="{{ post.link }}" class="more" target="_blank">More</a>
       </div>

       <div ng-show='loading' class='loading'>Loading...</div>
     </div>

  </body>
</html>

5. CSS

Create a style.css file.

Completed Code

.container{
  width: 55%;
  margin: 0 auto;
  border: 0px solid black;
  padding: 10px 0px;
}

/* post */
.post{
  width: 97%;
  min-height: 200px;
  padding: 5px;
  border: 1px solid gray;
  margin-bottom: 15px;
}

.post h1{
  letter-spacing: 1px;
  font-weight: normal;
  font-family: sans-serif;
}


.post p{
  letter-spacing: 1px;
  text-overflow: ellipsis;
  line-height: 25px;
}


/* more link */
.more{
  color: blue;
  text-decoration: none;
  letter-spacing: 1px;
  font-size: 16px;
}

/* Loading Message */
.loading{
  color: red;
  font-weight: bold;
  text-align: center;
}

6. PHP

Create a ajaxfile.php file.

Read POST row and rowperpage values.

Fetch records from posts table and use $row and $rowperpage to set LIMIT.

Loop on the fetched records and initialize $data Array.

Return $data Array in JSON format.

Completed Code

<?php

// configuration
include 'config.php';

$data = json_decode(file_get_contents("php://input"));

$row = $data->row;
$rowperpage = $data->rowperpage;

// Fetch data
$query = 'SELECT * FROM posts limit '.$row.','.$rowperpage;

$result = mysqli_query($con,$query);

$data = array();
while($row = mysqli_fetch_assoc($result)){
   $id = $row['id'];
   $title = $row['title'];
   $content = $row['content'];
   $shortcontent = substr($content, 0, 160)."...";
   $link = $row['link'];

   $data[] = array(
          "id"=>$id,
          "title"=>$title,
          "shortcontent"=>$shortcontent,
          "link"=>$link,
          "content"=>$content);

}

echo json_encode($data);

7. Script

Create a script.js file. Here, write AngularJS script.

Add infinite-scroll dependency to the module.

Define $scope variables –

  • $scope.row – Record selection position.
  • $scope.rowperpage – Number of records fetch at a time. I have assigned 3. You can change it according to your requirement.
  • $scope.posts – Assign AJAX response data.
  • $scope.busy – To not trigger scroll event when data is appending.
  • $scope.loading – To show hide the loading message.

Define a single method –

  • $scope.getPosts – This method is called when reaching to the bottom while scrolling.

Send AJAX POST request where pass $scope.row and $scope.rowperpage.

On successful callback update the $scope.row value. Loop on the response.data and assign in $scope.posts Array.

To display content after page load calls the getPosts() method.

Completed Code

var fetch = angular.module('myapp', ['infinite-scroll']);

fetch.controller('fetchCtrl', ['$scope', '$http', function ($scope, $http) {

  // Variables
  $scope.row = 0;
  $scope.rowperpage = 3;
  $scope.posts = [];
  $scope.busy = false;
  $scope.loading = false;

  // Fetch data
  $scope.getPosts = function(){

  if ($scope.busy) return;

    $scope.busy = true;

    // Fetch data
    $http({
      method: 'post',
      url: 'ajaxfile.php',
      data: {row:$scope.row,rowperpage:$scope.rowperpage}
    }).then(function successCallback(response) {

      if(response.data !='' ){
         // New row value 
         $scope.row+=$scope.rowperpage;

         $scope.loading = true;
         setTimeout(function() {
            $scope.$apply(function(){

              // Assign response to posts Array 
              angular.forEach(response.data,function(item) {
                 $scope.posts.push(item);
              });
              $scope.busy = false;
              $scope.loading = false;
            });

         },500);
      }

    });
  }

  // Call function
  $scope.getPosts();

}]);

8. Demo

Scroll the page.


9. Conclusion

Add infinite-scroll attribute to the container and pass the method which you want to call when reaching the bottom.

From the method send AJAX request to fetch data.

You can learn about more attributes of the ngInfiniteScroll directive from here.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *