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:

|X-Firefox-Spdy|h2|
|---|---|
|cache-control|max-age=0|
|content-encoding|gzip|
|content-length|3846|
|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|
|referrer-policy|no-referrer|
|server|Apache|
|strict-transport-security|max-age=16070400|
|vary|Accept-Encoding|
|x-ua-compatible|IE=edge|

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

THX!

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

<?php

// 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:

<?php

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

    $posts = $page->children()
                  ->visible()
                  ->flip();
    $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(
      'offset',
      'limit',
      'posts',
      'more',
      'last'
    );
};

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);
error_reporting(E_ALL);

… 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!