0

When I'm using controller function with parameters the rendered view just seems to forget every included .js files.

public function view($id = null) {
    if(!$id) {
        throw new NotFoundException(__('Invalid post'));
    }

    $post = $this->Post->findById($id);

    if(!$post) {
        throw new NotFoundException(__('Invalid post'));
    }
    $this->set('post', $post);
}

If I take parameters away and put variable '$id = 1' on function the view with postID 1 renders okay in 'posts/view'.

I included javascript files to default.ctp in traditional way:

echo "script type='text/javascript' SRC='../js/jquery-1.9.1.min.js'></script>";);

(it includes '<' but this text editor won't me type it for safety reasons I guess)

I don't have knowledge about 'js helpers' of cakePHP. Can't I use javascript in traditional way?

Site renders okay in every other view (e.g. posts/add) and .js files are included in source code of 'posts/view/1'

1 Answer 1

2

The problem

You're using relative paths to the javascript;

<script src='../js/jquery-1.9.1.min.js'></script>

In this url, ../ means '1 directory up from the current location`, so when you're currently visiting this URL;

http://mysite.com/home/

Then your browser will correctly try to load the script from;

http://mysite.com/js/jquery-1.9.1.min.js

However, if you're visiting this url;

http://mysite.com/home/and/some/more/

Then the browser will look for the JavaScript here:

http://mysite.com/home/and/some/js/jquery-1.9.1.min.js

How to fix the problem

  1. Use absolute paths for all 'assets' (CSS, JavaScript, Images); src='/js/jquery-1.9.1.min.js'
  2. Output the script-tags using CakePHP Helpers (after all, that's what they are meant for: to simplify your work :), e.g. echo $this->Html->script('jquery-1.9.1.min');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Now that seems pretty obvious

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.