Jump to content

passing over variable to JS via $config->js()


ngrmm
 Share

Recommended Posts

By default, the ProcessWire object is only output in the backend or if you have frontend editing active. Otherwise, you need to add it to the html head in your your php template like this:

<script>
  var ProcessWire = {config: <?= wireEncodeJSON($config->js(), true, $config->debug) ?>};
</script>

 

  • Like 3
Link to comment
Share on other sites

3 hours ago, BitPoet said:

 

<script>
  var ProcessWire = {config: <?= wireEncodeJSON($config->js(), true, $config->debug) ?>;
</script>

 

thx @BitPoet

I guess there is Typo in your Snippet. Missing closing }?
However I get a 500 Error.

So I tried this:
 

<script type="text/javascript">
	<?php $jsConfig = $config->js(); ?>
	var ProcessWire = {config: <?php echo json_encode($jsConfig); ?>};
	var config = ProcessWire.config;
</script>
 

and

$config->js('mySettings', [
	'foo' => 'bar',
]);

but console.log(ProcessWire.config); outputs an empty array

Link to comment
Share on other sites

2 hours ago, ngrmm said:

I guess there is Typo in your Snippet. Missing closing }?

Yes. Sorry.

2 hours ago, ngrmm said:

but console.log(ProcessWire.config); outputs an empty array

Not sure what's the error with wireEncodeJSON, might be a namespace issue or something else. But your code looks fine to me. Maybe outputting $jsConfig in a comment block or calling json_last_error_msg() can give you a clue about the empty array.

Link to comment
Share on other sites

14 hours ago, ngrmm said:

I would like to pass over a string from PHP to JS.

Is there a particular reason why you need to use config->js() for this? In a template file, the following should work just fine:

<?php

namespace ProcessWire;

$mydata = ['foo' => 'bar', 'bar' => 123];
$script = "<script>const mySettings = " . json_encode($mydata) . ';</script>';
echo $script;

// OR: $content.= $script; if using delayed output with automatic inclusion of _main.php, for example.

In the console...

test_pass_data_to_js_from_pw.thumb.png.6c272c96cf554ed54e2c4977d2baab8c.png

Edited by kongondo
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...