4

I have searched the web and mostly using jquery and some library to do so. I wonder how we can do it using pure javascript to make an Infinite Page Scroll Effect like twitter does without having to include any library(here i put the search php and html code for reference, and i wanna realize the effects in the search results. I use laravel as a backend). And i am just starting to learn javascript , please treat me as a 10 year old boy. Thanks

//HTML

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Risky Jobs - Search</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>

   <div class="searchWrapper">
      <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method='get' >
        <input type="search" name="search">
      </form>
   </div>

   <h3>Risky Jobs - Search Results</h3>

</body>
</html>

// PHP

function build_query($user_search, $sort){
    $search_query = "SELECT * FROM posts";

    $clean_search = str_replace(',',' ',$user_search);
    $search_words = explode(' ', $clean_search);
    //to  become a array

    $final_search_words = array();
    if(count($search_words) > 0){
        foreach($search_words as word){
            if(!empty($word)){// there are circustances that the user input two or more blank so it will result to a blank result
                $final_search_words[] = $word;


            }
        }
    }



    // Generate a WHERE clause using all of the search keywords
    $where_list = array();
    if(count($final_search_words) > 0){
        foreach($final_search_words as $word){
            $where_list[] = "content Like '%$word%'";
        }
    }
    $where_clause = implode(' OR ', $where_list);

    //Add the keyword WHERE clause to the search query
    if(!empty($where_clause)){
        $search_query .= " WHERE $where_clause";
    }




    // Sort the search query using the sort setting
    switch ($sort) {
        // Ascending by title
        case 1:
            $search_query .= " ORDER BY title";
            break;
        // Desending by title  
        case 2:
            $search_query .= " ORDER BY title DESC";
            break; 

        // Ascending by created_at
        case 3:
            $search_query .= " ORDER BY created_at";
            break;
        // Descending by created_at
        case 4:
            $search_query .= " ORDER BY created_at DESC";
            break;     
        default:
            // No sort setting provided, so don't sort the query
            //break;
    }

    return $search_query;

} //END OF build_query() FUNCTION


// This function builds heading links based on the specified sort setting

function generate_sort_links($user_search, $sort){
    $sort_links = '';

    switch ($sort) {
        case 1:
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=2">Title</a></td><td>Description</li>';
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=4">created_Time</a></td><td>Description</li>';
            break;
        case 3:
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=4">created_Time</a></td><td>Description</li>';
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=2">Title</a></td><td>Description</li>';
            break;

        default:
            $sort_links .= '<li><a href = "' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=3">created_Time</a></td><td>Description</li>';
    }

    return $sort_links;

}//end of  generate_sort_links




 // This function builds navigational page links based on the current page and the number of pages
function generate_page_links($user_search, $sort, $cur_page, $num_pages) {
    $page_links = '';

    // If this page is not the first page, generate the "previous" link
    if($cur_page >1){
      $page_links .= '<a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . ($cur_page - 1) . '"><-</a> ';
    }else{
        $page_links .= '<- ';
    }

    // Loop through the pages generating the page number links
    //loop through all the pages
    for($i = 1; $i <= $num_pages; $i++){
        if($cur_page == $i){
            $page_links .= ' ' . $i;
            //if current page, get rid of the url
        }else{
            $page_links  .= ' <a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . $i . '"> ' . $i . '</a>';
            //if not current page, add the url to make it point to next page or previous page
        }

    }


    //// If this page is not the last page, generate the "next" link
    if($cur_page < $num_pages){
        $page_links .= ' <a href="' . $_SERVER['PHP_SELF'] . '?usersearch=' . $user_search . '&sort=' . $sort . '&page=' . ($cur_page + 1) . '">-></a>';
        //if not last page, make -> have a url and can point to the previous one
    }else{
        $page_links .= ' ->';
    }


    return $page_links;

}//end of generate_page_links function




 // Grab the sort setting and search keywords from the URL using GET

 $sort = $_GET['sort'];
 $user_search = $_GET['usersearch'];

 //// Calculate pagination information
 $cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
 $result_per_page = 5;// number of results per page
 $skip = (($cur_page -1) * $results_per_page);


 // Start generating the search results
 echo '<div class="filter">';
 echo generate_sort_links($user_search, $sort);
 echo '</div>';

 // Connect to the database
  require_once('dbinfo.php');
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);


  // Query to get the total results 
  $query = build_query($user_search, $sort);
  $result = mysqli_query($dbc, $query);

  $total = mysqli_num_rows($result);
  $num_pages = ceil($total / $results_per_page);

  // // Query again to get just the subset of results
  $query = $query . " LIMIT $skip, $results_per_page";
  //limit 10,5 means skip the 10 and return 5  
  //$skip = (($cur_page -1) * $results_per_page);

  $result = mysqli_query($dbc, $query);
  while ($row = mysqli_fetch_array($result)) {
    echo '<div class="search_item">';
    echo '<div>' . $row['title'] . '</div>';
    echo '<div>' . $row['created_at'] . '</div>';
    echo '<div>' . substr($row['content'], 0,300) . '</div>';
    echo '</div>';//end of search_item wrap
  }


   // Generate navigational page links if we have more than one page
  if($num_pages >1 ){
    echo generate_page_links($user_search, $sort, $cur_page, $num_pages);
  }

  mysqli_close($dbc);
Frank Lee
  • 161
  • 10

2 Answers2

2

Here you can find an easy way to do an infinite scroll:

JS:

var callback = function test() {

    // Log how the height increases to the console
    console.log(document.getElementById('infinite').style.height)

    // equivalent to $('#infinite') in jQuery
    var el = document.getElementById('infinite');
    var newHeight = document.getElementById('infinite').offsetHeight + 200;

    // Update the height property of the selected element
    el.style.height = newHeight + 'px';
}

window.addEventListener('scroll', callback, false);

Basically adding an event listener attached to the scroll, so, every time we scroll, that function is triggered and increase the height property of the element.

You will just need a div as:

<div id='infinite' style='height: 2000px'></div>

Here's a fiddle

Hope it helps :)

Alex.U
  • 1,631
  • 2
  • 16
  • 26
  • What if I use nav like 1,2,3,4 ~in the bottom which I just query the database 5 item a time? – Frank Lee Dec 09 '15 at 21:53
  • for example, i wanna get a search result from the database. if we use infinite scrolling , then shouldn't we get a certain amount of data from the database one at a time when users scroll to the bottom. And now I have a site with nav at the bottom , how could i change that to infinte scrolling? – Frank Lee Dec 10 '15 at 11:24
  • @FrankLee you changed the specification of the question to something completely different, from "how to make an infinite scroll using pure javascript" to "how to make an Infinite Page Scroll Effect in Static page using pure javascript and also i wonder how to use these pure php code into laravel". Next time, be more specific instead of wasting our time. Simply make another question with the new requirement instead of changing the current one. – Alex.U Dec 10 '15 at 13:38
  • sorry,i will change that. – Frank Lee Dec 11 '15 at 07:07
  • And in your way above, i need to query all the data at one time rather than 5 pieces of a time like my code above did, will that be inefficient? – Frank Lee Dec 11 '15 at 07:16
1

What you need to do is an Ajax call on scroll, which appends the products. This question has been asked before and answered over here: On Scroll down how to make ajax call and get the respone data

The code executes an ajax call when a user reaches at end of page. By keeping track of the amount of products, you could send the offset and limit with the ajax call so you could use that within your database query.

EDIT: Look what I just found: http://www.smarttutorials.net/infinite-scroll-using-jquery-ajax-php-and-mysql/ If this doesn't help...

EDIT 2: No wordpress so code removed

Community
  • 1
  • 1
Erik van de Ven
  • 4,747
  • 6
  • 38
  • 80
  • not quite solve my problem,look at my php code for search and i wanna change from that – Frank Lee Dec 10 '15 at 12:05
  • You should call your PHP coded page with Ajax. And it would be better to extend the function so you need to give the "offset" and "limit" as parameters also, so you could send those parameters using the Ajax call. Then you're able to use infinite scroll as alternative to pagination. Sorry, I don't have the time right now to write all the code, but I hope this helps. – Erik van de Ven Dec 10 '15 at 12:10
  • if available, can you post the code ,thanks^_^, and the link is helpful too. – Frank Lee Dec 11 '15 at 08:21
  • alright. I see you use wordpress, so I will post some example code which you could use to make this work. As soon as I'm home. In about an hour – Erik van de Ven Dec 13 '15 at 16:26
  • @FrankLee check my code. This should help you, right? If you need more variables to pass to the Ajax function, just add more keys like the `limit` and `offset` keys inside the functions.js file. – Erik van de Ven Dec 13 '15 at 18:45
  • Sorry, I am not using wordpress, actually I am using laravel in my backend . And in the code above, it's pure php code, without any framework. – Frank Lee Dec 13 '15 at 22:10
  • damn it, my bad. Well in that case, just google it. There are so many pages which explain how to do an infinite scroll using the laravel framework: https://www.google.com/search?q=infinite%20scroll%20laravel&rct=j – Erik van de Ven Dec 14 '15 at 08:52