James Dawson James Dawson - 5 months ago 25
PHP Question

Generating Javascript view block with CakePHP

Consider a URL like this:

http://site.com/upload/qeSJGs,ZWURb4,qdMMTZ,yM62UX,RlwwWT,ecw7s1


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

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)); 
Comments