4

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?

2 Answers 2

4

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)); 
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Was this the answer you were looking for?
3

For Cakephp 2.x and Cakephp 3.x You can use:

In View or Template file:

<?php $this->Html->scriptStart(array('block' => 'scriptBottom', 'inline' => false)); ?>

$(document).ready(function(){
  console.log('OK');
});

<?php $this->Html->scriptEnd(); ?>

In Layout file:

<?= $this->fetch('scriptBottom'); ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.