Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stavrossk/6c3d6c3a7f5a2d9fc6ea7b92d75d5f79 to your computer and use it in GitHub Desktop.
Save stavrossk/6c3d6c3a7f5a2d9fc6ea7b92d75d5f79 to your computer and use it in GitHub Desktop.
Passing variables and data from PHP to JavaScript using the DOM.
<!-- snip -->
<div id="dom-target" style="display: none;">
<?php
$output = "42"; //Again, do some operation, get the output.
echo htmlspecialchars($output); /* You have to escape because the result
will not be valid HTML otherwise. */
?>
</div>
<script>
var div = document.getElementById("dom-target");
var myData = div.textContent;
</script>
<!-- snip -->

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Pros Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly. Cons Potentially Unsemantic Markup - Usually, what happens is that you use some sort of to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements. Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source. Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself. Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment