Data 'more' error with ajax

hello

I’m getting an error on $data['more'] = $more; when I type http://localhost/mysite/.json.
I’m trying to add an “Ajax load more” function on the homepage. The limit is working good, and all the console logs are ok too, but when I click on the “load-more” button, nothing happen. So I went to /.json and saw that weird error I can’t tell where does it come from ?..

home.php template

<ul class="projets" data-page="<?= $page->url() ?>" data-limit="<?= $limit ?>">
    <?php foreach($projects as $projet): ?>
    <?php snippet('projet', compact('projet')) ?>
    <?php endforeach ?>
</ul>

controller home.php

<?php
return function($site, $pages, $page) {
  $projects = page('projets')->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    = 4;
    $projects = $projects->limit($limit);
  }
  return compact('offset', 'limit', 'projects', 'more', 'projets');
};

home.json.php

<?php
$html = '';
foreach($projects as $projet) {
  $html .= snippet('projet', compact('projet'), true);
}
$data['html'] = $html;
$data['more'] = $more;
echo json_encode($data);

script.js

$(function(){
        var element = $('.projets');
        alert(element);
        var url     = element.data('page') + '.json';
        alert(url);
        var limit   = parseInt(element.data('limit'));
        alert(limit);
        var offset  = limit;
        $('.load-more').on('click', function(e) {
            alert("on click");
            $.get(url, {limit: limit, offset: offset}, function(data) {
                if(data.more === false) {
                    $('.load-more').hide();
                }
                element.children().last().after(data.html);
                offset += limit;
            });
        });
    });

The $more variable is not defined if you call the URL directly in your browser, so there’s nothing wrong with that. To test if your json template works in the browser, comment out the incriminating line in the template.

If you are using this on the home page, you have to add a slash when calling the URL in your script:

var url     = element.data('page') + '/.json';

Arg ! :speak_no_evil:
I knew that but I forgot!
It’s the fastest problem solving in the world!

Happy New Year Texnixe, and have a good day !

Thank you, and a Happy New Year to you, too.

Time to update the recipe.