简体   繁体   中英

Infinite scroll in Symfony using Ajax

I wanted to show products from db using infinite scroll.

Here is my Controller:

    $start=0;
    $limit= 6;

    $query = $repository->createQueryBuilder('classified')
        ->join('classified.statusId','status')
        ->andWhere('status.name=:status')
        ->setParameter('status','active')
        ->setFirstResult($start)
        ->setMaxResults($limit)
        ->getQuery();

      $results = $query->getResult();

    if ($request->isXmlHttpRequest()){

        $list = $this->renderView('search-result.html.twig', [
            'results' => $results
        ]);


    $response = new JsonResponse();
    $response->setData(array('classifiedList' => $list));
    return $response;
}

Ajax:

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

        })

        function getmoredata() {
            $.ajax({
                type: "GET",
                url: "{{ path('classified_list', {'type' : 'all'}) }}",
                dataType: "json",
                cache: false,
                success: function (response) {
                        $('.card-deck').append(response.classifiedList);
                        $('#spinner').hide();
                        console.log(response);

                },
                error: function (response) {
                    console.log(response);
                }
            });
        }

So now what is happening is the first 6 results is repeatedly showing when the scrolling is triggered. I know this is not correct and I don't expect this to work properly. But what I don't know is what is the next step. So do I need to add paginator or something?

Any help would be appreciated,Thanks!

You need to track whether your ajax is requesting or not, so it will not do request multiple times when window reach the scroll limit. Also, you need to track the offset and whether you have more data to loads. eg

 window.__isFetching = false;
 window.__offset = 0;
 window.__hasMoreData = true;

 $(window).scroll(function () {
    if($(window).scrollTop() + $(window).height()>= $(document).height()){

      if(!window.__isFetching && window.__hasMoreData) {
         getmoredata();
      }
    }

 })

 function getmoredata() {
        window.__isFetching = true;
        $.ajax({
            type: "GET",
            // NOTE, you can pass current offset here in url
            url: "{{ path('classified_list', {'type' : 'all', }) }}"+"&offset="+window.__offset,
            dataType: "json",
            cache: false,
            success: function (response) {
                    $('.card-deck').append(response.classifiedList);
                    $('#spinner').hide();
                    console.log(response);

                   // Note that here, server side response must have next offset and hasMoreData attribut.
                    window.__isFetching = false;
                    window.__hasMoreData = response.hasMoreData;
                    window.__offset = response.offset

            },
            error: function (response) {
                console.log(response);
            }
        });
  }

in server side , which is symfony, you might want to do something like:

// Get offset from request query
$start= $request->query->get('offset');
$limit= 6;

$query = $repository->createQueryBuilder('classified')
    ->join('classified.statusId','status')
    ->andWhere('status.name=:status')
    ->setParameter('status','active')
    ->setFirstResult($start)
    ->setMaxResults($limit)
    ->getQuery();

  $results = $query->getResult();

if ($request->isXmlHttpRequest()){

    $list = $this->renderView('search-result.html.twig', [
        'results' => $results
    ]);


$response = new JsonResponse();
// And add offset and hasMoreData fields in response
$response->setData(array(
  'classifiedList' => $list,
   'offset' => $start += 1
   'hasMoreData' => count($list) < ($limit * &start)
  )
);
return $response;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM