James Dawson James Dawson - 2 years ago 111
PHP Question

Generating Javascript view block with CakePHP

Consider a URL like this:


I need to get all of the 6 character strings separated by
into a Javascript array and inserted into my page. Here's my controller action:

public function upload($imageHashes) {
$this->set('title_for_layout', 'Uploads successful');
$this->set('imageHashes', explode(',', $imageHashes);
$this->layout = 'complex';

and in my view file I have this:

<?php echo $this->Html->scriptBlock('', array('inline' => false)); ?>

Now, it's going to be mighty messy to write all the Javascript in the
method, but I can't include an external Javascript file because the content changes based on the URL. Is there an easier way to do this that I'm not aware of?

Answer Source

Take your imageHashes array and json_encode it. Then for your script block you can just do something like

echo $this->Html->scriptBlock('var jsArray = ' . $json_encoded_array . ';', array('inline' => false)); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download