1

I've set this up so that a main blog page displays an initial 3 posts, with tags when loaded fully.

            [[!getResourcesTag? 
                &element=`getResources` 
                &elementClass=`modSnippet`
                &tpl=`blog-item`
                &tplFirst=`blog-item-featured`
                &limit=`3`
                &hideContainers=`1` 
                &parents=`5` 
                &tagKey=`blog-tags`
                &includeTVs=`1`
                &tvPrefix=``
            ]]

The initial 3 posts displayed are sorted by date order on the main landing page (most recent first) e.g. Article 1, Article 2 & Article 3.

On clicking a "more posts" button underneath the 3 posts that are displayed, infinite scroll pagination (which has been set-up) kicks in.

<button class="load-more" data-parent="5" data-current-page="1">More Posts</button>

But when clicking on More Posts - Article 3 (again) & Article 4 are returned - instead of Article 4 & Article 5.

 $method   = $modx->getOption('method', $scriptProperties, 'initial');
 $limit    = $modx->getOption('limit', $scriptProperties, 3);
 $parent   = $modx->getOption('parent', $scriptProperties);
 $tpl      = $modx->getOption('tpl', $scriptProperties);
 $tplFirst = $modx->getOption('tplFirst', $scriptProperties);

 $load   = (int) $_GET['page'];
$offset = 0;

if($method == "initial") {
    if($load != 0) {
        $limit = $limit * $load;
    }
} elseif($method == "pagination") {
    $offset = $limit * ($load - 1);
}

$page = $modx->runSnippet('getResources', array(
    'parents'        => $parent,
    'limit'          => $limit,
    'offset'         => $offset,
    'includeTVs'     => '1',
    'tvPrefix'       => '',
    'includeContent' => '1',
    'tpl'            => $tpl,
    'tplFirst'       => $tplFirst
));

I've played about with parameters & tried altering the code that deals with offset but can't seem to figure it out.

Some help would be great.

cab
  • 33
  • 6

1 Answers1

1

UPDATED CODE ADDED

I did something similar a while back, almost exactly actually [must have googled it]

the only difference in my inital getResources call is I used an offset of 0

<div id="posts">
<!-- get first few articles -->
[[!getResources?
     &parents=`10,22`
     &depth=`999`
     &limit=`6`
     &offset=`0`
     &includeTVs=`1`
     &processTVs=`1`
     &includeContent=`1`
     &tpl=`infiniteHomePageTpl`
     &sortby=`publishedon`
     &showHidden=`1`
     &hideContainers=`1`
]]

</div>

<button id="scroller" class="btn btn-primary load-more" data-parents="10,22" data-offset="6" data-posts="3">Show More Articles</button>
<button id="scolltotop" class="btn btn-primary scrollToTop" style="display:none;">Back to Top</button>

Just for Brevity, here is the snippet and js:

<?php
    $output = array(
      'status' => 'success',
      'msg' => 'message',
      'data' => 'blaaaaaaaah',
      'lastpost' => FALSE,
    );

    $properties = $scriptProperties['data'];

    $modx->log(modX::LOG_LEVEL_ERROR,'Running processor: ajax.generic, scriptProperties = '. print_r($properties, TRUE));

    $limit  = $properties['limit'];
    $parents = $properties['parents'];
    $tpl    = $properties['tpl'];
    $offset = $properties['offset'];
    $depth = $properties['depth'];
    $sortby = $properties['sortby'];
    $debug = $properties['debug'];
    $showHidden = $properties['showHidden'];
    $hideContainers = $properties['hideContainers'];

    $modx->log(modX::LOG_LEVEL_ERROR, 'tpl = ' . $tpl);

    $posts = $modx->runSnippet('getResources', array(
        'parents'       => $parents,
        'depth'         => $depth,
        'limit'         => $limit,
        'offset'        => $offset,
        'includeTVs'    => '1',
        'processTVs'    => '1',
        'includeContent' => '1',
        'tpl'           => $tpl,
        'debug'         => $debug,
        'sortby'        => $sortby,
        'showHidden'    => $showHidden,
        'hideContainers'=> $hideContainers,
    ));

   $output['posts'] = '<div class="post-group" style="display:none" >' . $posts . '</div>';

   if(strlen($posts) == 0){

   $output['lastpost'] = TRUE;

   }

   $output = $modx->toJSON($output);

    return $output;

and the JS:

// infinite scrolling on homepage
    // use: <button id="scroller" class="btn btn-primary load-more" data-parents="10,22" data-offset="0" data-posts="5">Show More Articles</button>
    $('.load-more').click(function(e) {

        var $this = $(this);

        var offset = $this.data('offset'); // the current offset for get resources

        var posts = $this.data('posts'); // the number of posts to get

        var parents = $this.data('parents'); // the parent ids to pull resources from

        var myProperties = {
            snippet: 'infiniteScroll',
            limit: posts,
            offset: offset,
            parents: parents,
            depth: 999,
            sortby: 'publishedon',
            showHidden: 1,
            debug: 1,
            tpl: 'infiniteHomePageTpl',
            hideContainers: 1
            };
console.log('props = ' + JSON.stringify(myProperties));
        $.ajax({
            type: "POST",
            url: "/ajax.processor",
            data: myProperties,
            dataType: "json",

            success: function(response) {

                var newposts = response.posts;

                var $div = $("div#posts");

                $div.append(newposts);

                $div.find(".post-group:last").fadeIn();

                $('body').stop().animate({scrollTop:$div.prop("scrollHeight") + $div.height()},1000);

                if(response.lastpost){
                    console.log('nodata');
                    $this.attr('disabled', 'disabled');
                    $this.html('no more posts');
                    $('.scrollToTop').show();
                }

                $this.data('offset', (offset + posts));

            },

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

        }).fail(function(jqXHR,textStatus,errorThrown) {
            console.log(errorThrown);
        }); // ajax

    }); // load more

    // scroll back to top on finished resources.

    $('.scrollToTop').click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
    });

Ajax Processor

<?php
//$modx->log(modX::LOG_LEVEL_ERROR,'Running processor: ajax.generic, snippet = '. print_r($_POST, TRUE));

$output = $modx->runSnippet($_POST['snippet'], array('data' => $_POST));

header('Content-type: application/json');

return $output;
Sean Kimball
  • 4,506
  • 9
  • 42
  • 73
  • Hi Sean, In integrating the code, I get the following in console: Object {status: "success", msg: "message", data: "blaaaaaaaah", lastpost: true, posts: ""} nodata – cab Jul 21 '15 at 19:13
  • looks like it's working then - you got the default success array back with ~some~ data, but probably the runsnippet didn't return anything. – Sean Kimball Jul 21 '15 at 19:33
  • Hmm, strange. Off the top of your head any ideas why the runsnippet has returned nothing? – cab Jul 21 '15 at 19:36
  • not really - the one gotcha I came across with runsnippet is tghat it only returns strings [no arrays, objects etc] but that does not look like the issue - you have the rendered chunk so it's doing something. build the array outside the snippet function and dump it so you see exactly what is being passed, then see if you can convince get resources to return debug info [don't specify the chunk and set debug to 1] or post your modified code – Sean Kimball Jul 22 '15 at 03:54
  • This is the Javascript that is being passed: `Object { snippet: "ajax-pagination", limit: 5, offset: 0, parents: 5, depth: 999, sortby: "publishedon", debug: 1, tpl: "blog-item" }` I'm getting a "POST 200 OK", so the data appears to be sent, but I'm getting [object Object] (undefined) returned. – cab Jul 22 '15 at 16:02
  • As an addendum, most of the code is the same as you kindly provided. I've been playing around with different solutions, but with no joy. – cab Jul 22 '15 at 16:16
  • Looks like I am missing my connector from my post - will update shortly, maybe there is a clue there. [you are converting back to json in your processor?] – Sean Kimball Jul 23 '15 at 14:43
  • I'm using almost identical JS to the code you kindly provided. Am I right in saying that using `dataType: "json"` automatically parses the data sent back to the Ajax call? I'm not using `JSON.parse()` if that's what you are meaning? – cab Jul 23 '15 at 15:07
  • No it's telling what type of data to expect back. http://stackoverflow.com/questions/2722750/ajax-datatype – Sean Kimball Jul 23 '15 at 15:10
  • I've uploaded the JS for you (I can do the same for PHP if required) http://s1148.photobucket.com/user/KrazeeKong/media/js_zpsffruo4sz.png.html – cab Jul 23 '15 at 17:04
  • `[object Object]` & `undefined` is returned in the AJAX call. The object appears to be posted successfully, but nothing is returned. I have tried different methods of sending the data. Here is c screenshot of the PHP, for the sake of completeness. http://s1148.photobucket.com/user/KrazeeKong/media/php_zpsib1qmqp5.png.html – cab Jul 23 '15 at 18:25
  • Cheers Sean, I updated the code as per your kind instruction. Unfortunately, nothing at all is now returned to the AJAX call (console is empty). – cab Jul 24 '15 at 18:24
  • I've upload this screenshot for you. As you can see the `echo $properties; ` displays nothing when the code is run - http://s1148.photobucket.com/user/KrazeeKong/media/new_zpsov4ucxnd.png.html – cab Jul 24 '15 at 18:37
  • Hey Sean, first off thanks for your help - much appreciated. I don't know if you had a chance to look at the screenshots I uploaded but I've spent a lot of time working with the code & I can't get it to work. Looks like I'll just have to leave it there. – cab Jul 27 '15 at 19:10
  • first off, make sure your getresources is returning something. turn on debugging and grab the query from your error log, run it against the database to verify. if it is, add some debugging to your processor to dump the data before it's sent and after it receives a response. Also in your snippet you are running runsnippet twice and overwriting your $output variable AND you need to convert it to json - because that is what your js is expecting back. – Sean Kimball Jul 28 '15 at 15:44