Well, first of all, your route has to return the page together with a data array, and your routing pattern is not correct, either.
But while this would work to give you the projects if set up correctly, it doesn’t help you any, because next time the controller is called via the Ajax call, the information will be lost.
Getting back to my last suggestion:
Controller:
<?php
return function($site, $pages, $page) {
// shuffle the collection
$projects = $page->children()->visible()->shuffle();
// pass all uids of the shuffled collection into an array
foreach($projects as $p) {
$data[] = $p->uid();
}
$count = $projects->count();
// check if the request is an Ajax request and if the limit and offset keys are set
if(r::ajax() && get('offset') && get('limit')) {
// get the data from the Ajax request
$collection = get('projects');
// create a new Pages object
$projects = new Pages();
// loop through the uids, get each page and add it to the $projects collection, restores the original shuffled collection
foreach($collection as $item) {
$projects->add(page('projects')->children()->findBy('uid', $item));
}
$offset = intval(get('offset'));
// convert limit and offset values to integer
$limit = intval(get('limit'));
// limit projects using offset and limit values
$projects = $projects->offset($offset)->limit($limit);
// check if there are more projects left
$more = $count > $offset + 1;
// otherwise set the number of projects initially displayed
} else {
$offset = 0;
$limit = 2;
$projects = $projects->limit($limit);
}
return compact('offset', 'limit', 'projects', 'more', 'projects', 'firstname', 'data');
};
Template: Add data-projects
attribute
<ul class="projects" data-page="<?= $page->url() ?>" data-limit="<?= $limit ?>" data-projects='<?= json_encode($data) ?>'>
Script:
$(function(){
var element = $('.projects');
var url = element.data('page') + '.json';
var limit = parseInt(element.data('limit'));
var offset = limit;
var projects = element.data('projects');
$('.load-more').on('click', function(e) {
$.get(url, {limit: limit, offset: offset, projects: projects}, function(data) {
if(data.more === false) {
$('.load-more').hide();
}
element.children().last().after(data.html);
offset += limit;
});
});
});
Edit: While this works, it’s probably not such a great idea with hundred of project titles printed out into the data attribute.