eng_mazzy
eng_mazzy

Reputation: 1049

passing php variable from controller to javascript function in the head of a view

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?

Upvotes: 0

Views: 4799

Answers (3)

mickmackusa
mickmackusa

Reputation: 47874

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:

  • they are harder for future script developers to quickly understand
  • they aren't able to enjoy array functions

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_encodeed 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.

Upvotes: 0

John Smith
John Smith

Reputation: 1814

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 ?>

Upvotes: 1

giorgio
giorgio

Reputation: 10202

yeah sure, just echo the javascript: <?php echo '<script>var myPhpVariable = "'. $my_var . '";</script>'; ?>

Upvotes: 5

Related Questions