prkmk
prkmk

Reputation: 363

Javascript in different folder than HTML

I'm new to web development. I have issues with having files stored in different folders (for safety reasons). Here's the index page which returns an error

<head>
   <script src="../scripts/script.js"></script>
</head>
<body>
   <?php include "../php/page.php"; ?>

   Other code here...
</body>

My file structure is as follows

www/
   html/
      index.php

   scripts/
      script.js

   php/
      page.php

I don't get why including php file works (row 5 in the example code provided) and including javascript doesn't (row 2). I guess you're interested about the error so here's what Google Chrome's console says

Failed to load resource: the server responded with a status of 404 (Not Found)

It also shows that link to the resource and it appears to look for my.server.address/scripts/script.js like it doesn't care the ../ part. Can someone explain this behaviour?

Upvotes: 0

Views: 6666

Answers (2)

user11272798
user11272798

Reputation:

Change

<script src="../scripts/script.js"></script>

to

<script src="/scripts/script.js"></script>

And your folder structure should be:

www/html/index.php
www/html/scripts/script.js
www/html/php/page.php

Upvotes: 1

Quentin
Quentin

Reputation: 943207

PHP resolves paths on the computer's file system.

Web browsers resolve paths on the URL.

Your HTTP server has http://my.server.address/ mapping to www/html on the file system.

So ../scripts/script.js goes up one level from / … to / (because that is the top), then down to /scripts then down to /scripts/script.js.

The browser asks the HTTP server for /scripts/script.js and it maps that to the file system — www/html/scripts/script.js and returns a 404 because that file doesn't exist there.

The browser can only read data that the web server will send to it, and by keeping the scripts directory outside of the document root you haven't make it available via the web server.

Upvotes: 7

Related Questions