Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and jquery Ajax and infinite scroll for filtering

I have applied the infinite-ajax-scroll to my project. It is a PHP Laravel project that displays a long list of divs. Instead of using pagination, I wanted to make the user see all results on the same page by scrolling down. I also have a filter for the results and it works well, but the strange thing is that after the results appear through filtering, scrolling down will lead to the appearance of all results without taking into account the current filter.

Can anyone advise on my best approach to this? I want to use the scrolling and it is something maybe realted to the url but I don't know how to fix this

Below is what I have so far.

// Filters

    // Search functions
    function storeSearchAjax() {
        var filters = searchFilters();

        $.ajax({
            method: 'get',
            data: filters,
            url: '/restaurants/search-ajax',
            success: function(data) {
                $('#result').html(data);
            }
        });
    }

    function searchFilters() {
        offerFilter = $(".offerCheckbox:checked").map(function () {
            return $(this).val();
        }).get();

        cuisineFilter = $(".cuisineCheckbox:checked").map(function () {
            return $(this).val();
        }).get();

        freedeliveryFilter = $(".freedeliveryCheckbox:checked").map(function () {
            return $(this).val();
        }).get();

        var filters = {
            "offers" : JSON.stringify(offerFilter),
            "cuisines" : JSON.stringify(cuisineFilter),
            "freedelivery" : JSON.stringify(freedeliveryFilter)
        }

        return filters;
    }

    // Paginate links
    $('#result .pagination li a').click(function(e) {
        e.preventDefault();

        var url = $(this).attr('href');
        var params = $.param(searchFilters());

        window.location = url+'&'+params;
    });


    $('input[name="offers[]"], input[name="cuisines[]"], input[name="freedelivery[]"]').change(function(e) {
        e.preventDefault();
        storeSearchAjax();
    });

          var page = 1;

            $(window).scroll(function() {
                if($(window).scrollTop() + $(window).height() >= $(document).height()) {
                    page++;
                    loadMoreData(page);
                }
            });

            function loadMoreData(page) {
                $.ajax({
                    url: '/restaurants/search?page=' + page,
                    type: "get",
                    beforeSend: function() {
                        $('.ajax-load').show();
                    }
                }).done(function(data) {


                    if(data.html=="") {

                        $('.ajax-load').html("");
                        return;
                    }
                    $('.ajax-load').hide();
                    $(".loading_restaurants").append(data.html);

                }).fail(function(jqXHR, ajaxOptions, thrownError) {
                    $('.ajax-load').html("server not responding...");
                
                });
            }

Controller :

    public function ajaxSearch(Request $request)
   {

       $stores = $this->getStores($request);
  
          Helper::usePaginate();
          $stores = $stores->paginate(15)->setPath('/restaurants/search');
  
          $cuisines = Storecuisine::getStoreCuisines();
          $storedays = Storeday::getStoreDays();
          $storewhours = Storeday::all();
          $isapp_open=Helper::isAppOpen();
  
          return response()->view('store-search.stores_listing', compact('stores','storedays','isapp_open','storewhours','cuisines'));
  }

1 Answers

function loadMoreData(page) {
    var filters = searchFilters();
    $.ajax({
        url: '/restaurants/search?page=' + page,
        data: filters,  // <-- this was missing
        beforeSend: function() {
            $('.ajax-load').show();
        }
    }).done(function(data) {
        if(data.html=="") {
            $('.ajax-load').html("");
            return;
        }
        $('.ajax-load').hide();
        $(".loading_restaurants").append(data.html);
    }).fail(function(jqXHR, ajaxOptions, thrownError) {
        $('.ajax-load').html("server not responding...");
    });
}

UPDATE

$(document).ready(function(){
    storeSearchAjax();
});

UPDATE 2

enter image description here

single scroll causing 10s of request !

Actually the scroll event is firing too many times even for a "light touch" creating many request for the same filter criteria you need to use some deboucing using library like lodash. So that the event fire less often and won't jam the browser or the server

Add lodash lib.

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>

Remove this code

  $(window).scroll(function() {
      if($(window).scrollTop() + $(window).height() >= $(document).height()) {
          page++;
          loadMoreData(page);
      }
  });

Add this instead

window.addEventListener('scroll', _.throttle(function(){
    if($(window).scrollTop() + $(window).height() >= $(document).height()) {
        page++;
        loadMoreData(page);
    }
}, 500));

UPDATE 3

For the second issue, don't increment page on scroll rather do on the ajax success callback. And also one more thing : currently its doing ajax even if we scroll up which is wrong instead it should do ajax only when we scroll down MORE than the previous deepest point for that you need to store the deepest scroll value in some variable and use that to compare whether use has scrolled MORE deep than the previously done

//create on global var say 
var deepestPoint = 0;

window.addEventListener('scroll', _.throttle(function(){
    if( 
       ( $(window).scrollTop() + $(window).height() >= $(document).height() )
       &&  ($(window).scrollTop() > deepestPoint )
    ) {
        page++; //<--Remove this from here
        loadMoreData(page);
        deepestPoint = $(window).scrollTop();
    }
}, 500));

//And then


 }).done(function(data) {
        if(data.html=="") {
           $('.ajax-load').html("");
           return;
        }

        $('.ajax-load').hide();
        $(".loading_restaurants").append(data.html);
        //<--paste here
 }).fail(function(jqXHR, ajaxOptions, thrownError) {
                $('.ajax-load').html("server not responding...");
 });
like image 147
Vinay Avatar answered Dec 07 '25 22:12

Vinay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!