Paul Paul - 9 months ago 41
PHP Question

Sending variables with functions assigned to them with JSON

I am attempting to add a date function I created to my JSON data that I am sending back with PHP. I cannot figure out how to properly assign the function in my separate php file and send back. The function is on my main page (comments page) and not in this php file.

However, on my main comments page, when not using JSON (just a normal PHP

query, the function works just fine.

I do it on my comments page (the page without the issue) like this:

$comment_array[] = $comment_date;
echo '<div class="comment-post-date">'.fixDate($comment_date). '</div>';

This is how I try to do it in the php file that isn't working when sent back. It is actually giving an error in the console:

Unexpected token <

I attempt to assign it as a variable and then send it back as this:

$html .= '<div class="comment-post-date">'.$fixed_comment_date. '</div>';

Full code:

if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
$comments = array();
foreach ($rows as $row) {
$comment_date = $row['date'];
$fixed_comment_date = fixDate($comment_date);
$html = "";
$html .= '<div class="comment-post-box" id="comment-'.$row['id'].'">';
//$html .= '<img class="home-comment-profile-pic" src="'.$row['img'].'">';
$html .= sprintf(
'<img class="home-comment-profile-pic" src="%s">',
empty($row['img']) ? 'profile_images/default.jpg' : $row['img']
$html .= '<div class="comment-post-info-block">';
$html .= '<div class="comment-post-username">'.$row['username']. '</div>';
$html .= '<div class="comment-post-date">'.$fixed_comment_date. '</div>';
$html .= '</div>';
$html .= '<div class="comment-post-text">'.$row['comment']. '</div>';
$html .= '</div>';
$data = array('id' => $row['id'], 'date' => $row['date'], 'html' => $html);
$comments[] = $data;
echo json_encode($comments);

Any ideas how I can get this to work?

Answer Source

Unexpected token < usually means your script didn't output JUST json. It output html+json, which is illegal JSON.

If you're doing a request for which JSON is expected as the response, then any OTHER output, other than the actual json response, will be treated as a JSON syntax error.


echo '<div>blahblalblah</div>';
echo json_encode($whatever):

will cause your unexpected token error, because the first < in the <div> line is already a JSON syntax error.

That also means that things like PHP warnings/errors that are output will also become part of the response, and ALSO trigger a syntax error.