Prdufresne
Prdufresne

Reputation: 296

Use PHP to embed JSON for use by Javascript

I'm working on using React (javascript) inside a WordPress plugin but my plugin requires some data retrieved from the database. I could probably retrieve the required data in javascript using jquery or an API call, but since the data will be static, it seemed more efficient to embed the data using php prior to rendering the DOM element with javascript.

I tried the following, but the <script> tag containing the json never appears in the DOM.

<?php

$events = \Civi\Api4\Event::get()
  ->addSelect('*')
  ->addOrderBy('start_date', 'ASC')
  ->setLimit(25)
  ->execute();

  echo "<script type=\"application/json\" id=\"eventList\">";
  echo json_encode($events);
  echo "</script>";
?>

<div id="civi-react-events">
    <h2>Loading...</h2>
</div>

Update

It turns out the code above works. It turned out to be a cache issue. Ctrl-Refresh is your friend.

Thank you to those who took the time to respond.

Upvotes: 1

Views: 122

Answers (1)

Manuel Guzman
Manuel Guzman

Reputation: 533

Sometimes, json_encode returns tags, texts, etc. with a wrong format. It may lead to break the script tag To ensure the json is fine to use, use the json_encode flags. I personally recommend using the following flags:

<?php

$jsonExportConst = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK;

$eventsJson = json_encode($events, $jsonExportConsts);

echo "<script type=\"application/json\" id=\"eventList\">{$eventsJson}</script>"

Upvotes: 1

Related Questions