1

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.

9
  • Are you sure ‍that $events contains an array of events? What is the return type of execute method? Commented Feb 5, 2023 at 17:21
  • 1
    You are actually certain that it does not appear in DOM (as in, verified in HTML source), or just that your code can't access it? Is it possible that your environment has output buffering on, and the buffer is modified at some point, leading to your script/JSON not appearing? Commented Feb 5, 2023 at 18:08
  • I use this query in another context, so I do know that it returns an array. I did check the source of the HTML page to verify that it wasn't there. I haven't even attempted to access it with my script yet. Commented Feb 5, 2023 at 18:49
  • Thanks for your update. If that's the case, the question is unlikely to be of much use to anyone else, it would be better to delete it Commented Feb 5, 2023 at 19:45
  • I don't believe I am able to delete it. It is a working example of using PHP to embed json in the DOM, so it may be of value. Commented Feb 6, 2023 at 13:22

1 Answer 1

1

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>"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.