I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript?
I have code that looks like this:
<?php
...
$val = $myService->getValue(); // Makes an API and database call
?>
I have JavaScript code that needs val
and looks along the lines of:
<script>
myPlugin.start($val); // I tried this, but it didn't work
<?php myPlugin.start($val); ?> // This didn't work either
myPlugin.start(<?=$val?> // This works sometimes, but sometimes it fails
</script>
There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.
In no particular order:
In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.
This method is considered the best, because your server side and client side scripts are completely separate.
With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:
/* Do some operation here, like talk to the database, the file-session
* The world beyond, limbo, the city of shimmers, and Canada.
*
* AJAX generally uses strings, but you can output JSON, HTML and XML as well.
* It all depends on the Content-type header that you send with your AJAX
* request. */
echo json_encode(42); // In the end, you need to echo the result.
// All data should be json_encode()d.
// You can json_encode() any value in PHP, arrays, strings,
//even objects.
<!-- snip -->
<script>
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); // New request object
oReq.onload = function() {
// This is where you handle what to do with the response.
// The actual data is found on this.responseText
alert(this.responseText); // Will alert: 42
};
oReq.open("get", "get-data.php", true);
// ^ Don't block the rest of the execution.
// Don't wait until the request finishes to
// continue.
oReq.send();
</script>
<!-- snip -->
The above combination of the two files will alert 42
when the file finishes loading.
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.
<input type=hidden>
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 <meta>
element for data about the document, and HTML 5 introduces data-*
attributes for data specifically for reading with JavaScript that can be associated with particular elements.With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.
<!-- 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 is probably the easiest to understand.
Implementation is relatively straightforward:
<!-- snip -->
<script>
var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->
Good luck!