I would pass two php variables from a codeigniter controller to a javascript function located to the head of my view. is it possible to do such thing?
or just set in your controller your variables
eg - in the controller
$data['newvar'] = $myvar_in_the_controller;
and then in the view in the javascript
<?php echo $newvar ?>
I have been developing a page that requires quite a lot of php data to be ported to the client-side.
I prefer to write DRY code and sought a better way to compose the script instead of line after line of javascript declarations.
Unfortunately, I had to break one of my high-tier coding principles: Never use variable variables". The reasons I don't endorse variable variables are:
In the technique to follow, I'll show how to serve up individual javascript declarations in a DRY fashion. I am tolerating the use of a variable variable in this case because it will be clear which variable names are being handled and no array functions will be used. For the record, I never endorse the use of extract()
and have never had a good reason to use it in any of my projects. (I am only using extract()
to mock the CI behavior.)
PHP: (Demo)
// declared in controller...
$data = [
'a' => -1.5,
'b' => false,
'c' => null,
'd' => 'stringy "string" thing',
'e' => range(3,10),
'f' => "0",
'g' => (object)['food' => 'bard'],
'h' => "not used",
];
// the CodeIgniter effect...
extract($data);
// in your view...
$portToJS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
echo "\n<script>\nlet ";
foreach ($portToJS as $i => $variable) {
echo (!$i ? '' : ",\n\t") , "{$variable} = " , json_encode(${$variable});
}
echo ";\n</script>";
Output:
<script>
let a = -1.5,
b = false,
c = null,
d = "stringy \"string\" thing",
e = [3,4,5,6,7,8,9,10],
f = "0",
g = {"food":"bard"};
</script>
It is a good idea to json_encode()
your variable values so that you don't need to bother with quoting nor quote escaping.
Ideally, I would prefer to pass a single json_encode
ed object, then just access the values from within that structure. However, I have adopted a very heavy project which has been handled by many different developers over the years. Rather than refactor heaps of templates and risk breaking something, I am using the above as a temporary improvement until a proper re-scripting is afforded.
yeah sure, just echo the javascript: <?php echo '<script>var myPhpVariable = "'. $my_var . '";</script>'; ?>