Array to JSON conversion adds '<'

Hey everyone,
I followed the ‘load more with AJAX’ tutorial and everything went fine - until now. I don’t know how (or why) but it seems now the echo json_encode($data) part adds a less-than sign just before the json content starts, throwing

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

// .. and that's the issue, JSON starting with '<':
<{"html": " /* some JSON stuff*/ ", "more" : true}

The request headers are:

|content-type|application/json; charset=UTF-8|
|date|Sat, 17 Feb 2018 00:17:15 GMT|
|expires|Sat, 17 Feb 2018 00:17:15 GMT|

I read on Stackoverflow that the lesser-than sign stems from a PHP error, but … where?


Looks as if you have a stray opening tag in the json template


// templates/home.json.php
$html = '';

foreach($posts as $post) {
  $html .= snippet('partials/post', compact('post', 'last'), true);

$data['html'] = $html;
$data['more'] = $more;

echo json_encode($data);

$posts & $last (last post) are defined in controllers/home.php:


  return function($site, $pages, $page) {

    $posts = $page->children()
    $count = $posts->count();
    $last = $posts->last();

    if(r::ajax() && get('offset') && get('limit')) {
      $offset = intval(get('offset'));
      $limit  = intval(get('limit'));
      $posts  = $posts->offset($offset)->limit($limit);
      $more   = $count > $offset + 1;
    } else {
      $offset  = 0;
      $limit   = $page->limit()->int();
      $posts   = $posts->limit($limit);

    return compact(

Apart from $last (and the custom $limit inside the else statement), this is right from the docs …

// Update: On another test site, the exact same code works BUT calling the .json file gives me Undefined variable: more ?!

If you open the JSON file directly, $more is not defined, so that is OK.

If a PHP error may have caused this, did you try to catch it?

You might want to try this in your PHP template …

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

… and/or this in your .htaccess (since you are running Apache, as seen above):

php_flag display_errors 1
1 Like

@daybugging Could you sort this out?

Totally, there was an include in my config.php that wasn’t resolved correctly (typo) - and the .htaccess directive revealed it so I could fix it!

Thanks again for your kind help!