Sure – it’s the same as from the cookbook Load More With Ajax example.
In a similar way to the small example you gave, right now I am just trying to get the program to recognize that there are projects and to load one on each click. Right now I click ‘load more’ and the button disappears because it thinks there are no projects to display.
Content
content/projects
– alexander
– – project.txt
– – picture.jpg
– beth
– – project.txt
– – picture.jpg
– jake
– – project.txt
– – picture.jpg
– james
– – project.txt
– – picture.jpg
– moran
– – project.txt
– – picture.jpg
– sam
– – project.txt
– – picture.jpg
– projects.txt
project.txt
Title: Alexander Project
----
Code
controllers/projects.php
<?php
return function($site, $pages, $page) {
$projects = $page->children()->visible();
$count = $projects->count();
if(r::ajax() && get('offset') && get('limit')) {
$offset = intval(get('offset'));
$limit = intval(get('limit'));
$projects = $projects->offset($offset)->limit($limit);
$more = $count > $offset + 1;
} else {
$offset = 0;
$limit = 2;
$projects = $projects->limit($limit);
}
return compact('offset', 'limit', 'projects', 'more');
};
snippets/footer.php
<?php
echo js([
'assets/js/jquery.min.js',
'assets/js/script.js'
]);
?>
snippets/project.php
<li class="project">
<a href="<?= $project->url() ?>" class="project-link">
<?php if($image = $project->image()): ?>
<img src="<?= $image->url() ?>" alt="<?= $image->alt_text()->html() ?>" />
<?php endif ?>
<div class="project-caption">
<h2 class="project-title"><?= $project->title()->html() ?></h2>
</div>
</a>
</li>
templates/projects.php
<?php snippet('header') ?>
<main class="main" role="main">
<h1><?= $page->title()->html() ?></h1>
<?= $page->text()->kirbytext() ?>
<ul class="projects" data-page="<?= $page->url() ?>" data-limit="<?= $limit ?>">
<?php foreach($projects as $project): ?>
<?php snippet('project', compact('project')) ?>
<?php endforeach ?>
</ul>
<button class="load-more">Load more</button>
</main>
<?php snippet('footer') ?>
templates/projects.json.php
<?php
$html = '';
foreach($projects as $project) {
$html .= snippet('project', compact('project'), true);
}
$data['html'] = $html;
$data['more'] = $more;
echo json_encode($data);
assets/js/script.js
$(function(){
var element = $('.projects');
var url = element.data('page') + '.json';
var limit = parseInt(element.data('limit'));
var offset = limit;
$('.load-more').on('click', function(e) {
$.get(url, {limit: limit, offset: offset}, function(data) {
if(data.more === false) {
$('.load-more').hide();
}
element.children().last().after(data.html);
offset += limit;
});
});
});