The JavaScript connection

Where are we?

In the previous lesson, we saw how to use a PHP variable to keep links and images working in a dynamic templating system. We got the Big Win of being able to reuse things like page headers on all pages of a site.

Let’s look at reusing JavaScript files. The goal is the same. Have one JavaScript file that’s included across all pages. If we want to change the JavaScript, change that one file, and every page is changed.

This lesson’s goals

By the end of this lesson, you should:

  • See that JavaScript contains file paths. The paths can be broken when inserting files with PHP.
  • See how to fix the problem by creating a JavaScript variable that’s set with PHP.

The problem

Here’s a page with an image and a link.

Sample page

Figure 1. Sample page

Try it, but ignore the Another link for the moment. (We’ll get back to it.)

Move the mouse over the image, and it changes. Move the mouse out, and it changes back. There are two different images. They are swapped in and out when the mouse moves over an <img> tag (more on that later).

Here’s the directory tree for the site.

Tree

Figure 2. Tree

There are two pages. One is /index.html, the one we’ve been looking at. There’s another page, /another/index.html. We’ll get to that later.

The images are in the library directory. The JavaScript that handles the image changing is in the file js-example.js. It’s in the library directory as well.

Why are the files in a separate library directory? Because they’re going to be reused across the site.

Here’s the HTML. No PHP yet.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript" src="library/js-example.js"></script>
    <title>JavaScript Example - Broken</title>
  </head>
  <body>
    <h1>JavaScript Example - Broken</h1>
    <h2>Home</h2>
    <p><img id="message" src="library/welcome.png" alt="Welcome"></p>
    <p><a href="another/index.html">Another</a></p>
  </body>
</html>

Figure 3. HTML

Look at line 12. There’s the <img> tag that shows the current image. It has an id of message.

The JavaScript that changes the image is in the file /library/js-example.js, referenced in line 6.

(Line 5 is a reference to the jQuery library on a Google server. It uses an absolute URL, and is not affected by the templating system.)

Here’s the contents of /library/js-example.js. This is the JavaScript code that does the image switching.

$(document).ready(function() {
  $('#message').hover(
      function(){
        $('#message').attr('src', 'library/go_away.png');
      },
      function(){
        $('#message').attr('src', 'library/welcome.png');
      }
    );
});

Figure 4. JavaScript

When the mouse goes over the image, the <img> tag shows go_away.png (line 4). When the mouse leaves the image, it’s set back to welcome.png (line 7).

So far, so good. Now try the page again. But this time, follow the Another link. This loads the page /another/index.php. As you can see in Figure 2, it’s in a subdirectory.

The image shows up. But when you move the mouse over the image, go_away.png doesn’t appear. What’s the deal?

It’s the same problem we had on the previous lesson. It’s the file paths. Remember, you’re looking at the file:

/another/index.html

This JavaScript executes:

... attr('src', 'library/go_away.png')

library/go_away.png is a relative path, so the browser looks for the file relative to the current page. It tries to load:

/another/library/go_away.png

But the file is not here.

Argh! Yet again!

You can download all the files from this example.

A JavaScript Fix

Let’s look at a fix that uses just JavaScript, not PHP. It uses a similar approach, though: Set a variable with the path to the root.

Let’s add a few lines to /index.html. This is the first page we saw, the one that worked. Here is the new head section of the page.

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript" src="library/js-example.js"></script>
    <script type="text/javascript">
      var path_to_root = ".";
    </script>
    <title>JavaScript Example - Fixed with JavaScript</title>
  </head>

Figure 5. JavaScript fix

Lines 7 to 9 are new. Line 8 creates a JavaScript variable called path_to_root. It’s set with – guess what? – the path from /index.html (the file the code is in) to the root of the Web site. /index.html is in the root directory. “.” means “stay right here.”

We change /another/index.php as well, the page that didn’t work. Here’s what it changes to:

<script type="text/javascript">
  var path_to_root = "..";
</script>

Figure 6. JavaScript fix for another file

The “..” says, “To get to the root, go up to the parent.”

Let’s say we had the file hippo/llama/lion/dog.html. It’s code would be:

<script type="text/javascript">
  var path_to_root = "../../../";
</script>

Figure 7. A long path

dog.html is in the subdirectory lion. Line 8 says, “To get to the root, go up a level, go up a level, and go up a level.”

So, on each page, we create a JavaScript variable with the path from that page to the root of the Web page.

Now, what do we do with that variable? Let’s change /library/js-example.js. Remember that’s the file with the JavaScript code that handles the image switching. Here’s the new code:

$(document).ready(function() {
  $('#message').hover(
      function(){
        $('#message').attr('src', path_to_root + '/library/go_away.png');
      },
      function(){
        $('#message').attr('src', path_to_root + '/library/welcome.png');
      }
    );
});

Figure 8. New JavaScript

path_to_root has the path from the page to the root. /library/go_away.png is the path from the root to the new image file. So:

path_to_root + '/library/go_away.png'

is the path from the page to the new image file.

You can try it. You can also download all the files. Note that everything works just fine.

W00f!

Doing it with PHP

We have a JavaScript line like this, to get the JavaScript code in the library files to work right:

var path_to_root = "..";

We did the same thing in the last lesson, to get the file paths in the library HTML files (like the header and footer) to work right. But we used PHP:

$path_to_root = '..';

We could combine them, and get rid of the duplication. We’d end up with something like this for the head section of a page:

<head>
<?php $path_to_root = '..'; ?>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script type="text/javascript" src="../library/js-example.js"></script>
  <script type="text/javascript">
    var path_to_root = "<?php print $path_to_root; ?>";
  </script>
  <title>JavaScript Example - Fixed with JavaScript</title>
</head>

Figure 9. PHP and JavaScript

Line 4 sets a PHP variable with the root path. Line 9 puts that into a JavaScript variable. With this approach, we only need to remember to set the PHP variable. The JavaScript variable will be set correctly.

/library/js-example.js doesn’t change. The variable it needs – path_to_root – is still set correctly.

For this to work, you need to rename the HTML files, giving them a .php extension. Remember that PHP statements are only executed in files that have the extension .php. Here is the new directory tree:

New tree

Figure 10. New tree

You can try this approach. You can also download the files.

Notice what you are doing here. Look at this again.

<script type="text/javascript">
  var path_to_root = "<?php print $path_to_root; ?>";
</script>

Part of Figure 9 (again). PHP and JavaScript

This puts something like this in the code sent to the browser:

<script type="text/javascript">
   var path_to_root = "..";
</script>

What we are doing is using PHP code to write JavaScript code!

This is so weird. But it’s done all the time. Browsers know how to run JavaScript, just as they know how to display HTML. We take advantage of this. We write PHP that writes JavaScript, just as we write PHP that writes HTML. The browser then does its thing with what we send it.

This is a good example of how computers work in layers. The PHP layer creates stuff for the HTML/JavaScript layer.

Layers

Figure 11. Layers

Each layer has languages it understands. The layer underneath it creates stuff in those languages.

Exercise: Fix the dog head

Try this site with a broken logo animation. Move the mouse over the logo image. It works on the first page, but not the others.

Download a zip file of the site. Fix it, using PHP and JavaScript variables.

You can check my solution and download a zip file of it.

But try it yourself first!

Upload your solution to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Summary

  • JavaScript files contain file paths, just like HTML files. The paths can be broken when you use PHP to insert library files.
  • You can fix the problem by creating a JavaScript variable in each file containing the path to the Web root. That variable is added to the JavaScript code in the library files.
  • The JavaScript variable can have its value set by PHP.

What now?

Let’s see where we are.

  • You learned how to insert one file into another with PHP’s require statement.
  • You learned that that causes problems with file paths.
  • You learned how to fix them. Use a PHP variable to store the path from a page to the root. Use that variable in library files, like headers and footers.
  • You learned that reusing JavaScript files can cause similar problems.
  • You learned how to fix them. Set a JavaScript variable from the PHP variable. Use the JavaScript variable in JavaScript library files, like files with nav bar code.

Let’s put this all together, and create a complete dynamic templating system for a Web site.


How to...

Lessons

User login

Log in problems? Try here


Dogs