Dr Design – Javascript to PHP

The waiting room is full! Join the queue — and the Good Dr. Design will see you next time! But for now, he’s rolling up his sleeves and lending a hand to today’s patients…

Dream Rollovers

Hi!
Can you tell me why all the rollovers that I make in Dreamweaver don’t work in Mac Explorer v.5? Is there any way to make them work? Thank you very, very much…
Amando from Mexico City.

Amando, I haven’t looked at Dreamweaver’s rollover Javascript. Sometimes simpler is better. I’m quite fond of Andy Mathews (Gravity Digital) simple rollover Javascript, which he posted some time ago on the SitePoint Forums. Perhaps you’ll have more luck with this one.

<script language="javascript"> 
<!--

// Pre-load images
if (document.images) {
 image1on = new Image();
 image1on.src = "images/about_us_on.gif";
 image1off = new Image();
 image1off.src = "images/about_us_off.gif";
}

function changeImages() {
 if (document.images) {
   for (var i=0; i<changeImages.arguments.length; i+=2) {
     document[changeImages.arguments[i]].src =  
     eval(changeImages.arguments[i+1] + ".src");
   }
 }
}

// -->
</script>

Here’s an example of its use in HTML:

<a href="about_us.shtml" onmouseover="changeImages('image1',  
'image1on')" onmouseout="changeImages('image1', 'image1off')">
<img name="image1" src="images/about_us_off.gif" border=0></a>
Tracking the Relatives

Hey Doc,
I’ve designed and set up a small Website exclusively for family pictures. I’m using the Apache server software on a home PC.

My question is: how can I track the people that come to the site? I have set up a login name and password, which should restrict access… however, as word of mouth gets around in the family I’m sure that I’ll get lots of hits from distant relatives, and given that I’m a curious person I would like to know who does log in.

I’ve set up one login name and password so I can’t distinguish the users in this way… I have also, through HTML code, set up a screen to ask for a name and then place a cookie on the user’s PC, so that they know how often they’ve been to the site (and eventually, can see if there are any updates on the site).
Gary

Gary, I know where you’re coming from. There’s nothing more fun than keeping up with the family gossip and finding out what the relatives are up to. I’d probably opt for a bit of server side scripting in PHP or ASP for this one. However, you may not be using any server-side scripting, so let’s see if we can hatch an ingenious plan to perform visitor monitoring from the client-side using Javascript!

The technique I’ll use assumes you have a Web log analysis tool, or you’re true geek and read over your log files. Check out this list of available log analysis tools. Popular packages that run on Linux servers include Webalizer, Analog and AWStats. You’ll also find log analysis programs that will run under Windows.

Now, for the fun…

The technique is a little "edgy". Known as "clear gif spyware" or a "Web beacon", some people resent that online advertisers use this technique to track visitors. But that’s exactly what we want to achieve. If you were running a commercial Website and used this method it would be advisable (and in tune with online privacy ethics) to disclose in your privacy policy that you track visitors using cookies.

A "Web beacon" uses Javascript to append a query string onto the address of a clear (transparent 1×1 pixel) gif, which is loaded into the Web page. The query string will be ignored by the Web server when it serves up the clear gif, except that the HTTP GET request will be logged in your Website access logs. When you analyse your logs, you’ll be able to trace your visitors through the requests for the clear gif. For example, you will have entries such as:

[10/Oct/2002:03:16:42 +0000] "GET /clear.gif?name=Mary HTTP/1.1"

Here’s the code for a page that tracks any "cookied" visitor through the function setGif(), and will also set a cookie with the user’s name wn they submit the form that asks them for their name.

<html> 
<head>
<script language = "javascript">

// set the cookie expiry date to be in twelve months
expireDate = new Date;
expireDate.setMonth(expireDate.getMonth() + 12);

// convert the expiry date to GMT format
cookieDate = expireDate.toGMTString();

// declare userName as global
var userName = "";

// setCookie() sets a cookie with the userName
// submitted by the form userForm
function setCookie() {
 userName = document.userForm.name.value;  
 cookieString = "userName=" + userName + "; expires=" +  
 cookieDate + ";";
 document.cookie = cookieString;
 alert('Welcome ' + userName + '!');

 // call function setGif() so that we track this visitor's page view
 // now that we know their name!
 setGif();
 return false;
}

// setGif() will embed the clear gif into the document
// and append the cookied userName so that we can track
// the user in our website access log.
function setGif() {
 if(document.cookie != "") {
   userName = document.cookie.split("=")[1];
   imageTag = '<img src="clear.gif?name=' + userName + '" width=1  
   height=1>';
   document.write(imageTag);
 }
}

</script>
</head>

<body>
<form name = "userForm">
Select a username:
<input type=text name="name" onBlur="return setCookie()">
<input type="submit" value="submit" onClick="return setCookie()">
</form>

<script language="javascript">
 setGif();
</script>
</body>
</html>

Variable Assignment Blues

Hello Doctor,
I have a quick question for you. I am new to PHP programming and have quickly found myself stuck. After connecting to a MySQL database through PHP, I am using the following PHP code to insert rows into an existing table…

   // If an artist has been submitted,  
   // add them to the database.  
   if ($addArtist == "Add") {  
     $sql = "INSERT INTO Artists SET  
     Name='$AddName',  
     bio='$AddBio';";  
     if (@mysql_query($sql)) {  
       echo("Artist Added");  
     } else {  
       echo("<p>Error adding submitted order: " .  
            mysql_error() . "</p>");  
 
     }  
   }

However, I need to also add rows into a different table under the same database at the same time. I have had no success with adding it this way (only one sql statement is recognized, not both)…

    // If an artist has been submitted,  
   // add it them the database.  
   if ($addArtist == "Add") {  
     $sql = "INSERT INTO Artists SET  
     Name='$AddName',  
     bio='$AddBio'";  
     $sql = "INSERT INTO Pictures SET  
     fileSRC='$AddPicture'";  
     if (@mysql_query($sql)) {  
       echo("Artist Added");  
     } else {  
       echo("<p>Error adding submitted order: " .  
            mysql_error() . "</p>");  
     }  
   }

I've looked everywhere and have not found a solution. Please let me know if you can help.
Thank you,
David

David, it always makes my heart rejoice to hear of someone finding the path to open source enlightenment and wisdom. You will be a master of PHP in no time!

Here is the problem with your second code example. When you assign your second query string to the variable $sql, this will "overwrite" the previous value of the variable, which is the first query string you assigned. Here's an example:

$myString = "foo";  
$myString = "bar";  
echo $myString;

This will output:
bar

However, if I write:
$myString = "foo";  
echo $myString;  
echo '<br>';  
$myString = "bar";  
echo $myString;

This will output:
foo  
bar

Back in your code, you might want to try something like this:

if ($addArtist == "Add") {  
 
  // first insert the record into Artists  
  $sql = "INSERT INTO Artists SET  
       Name='$AddName',  
       bio='$AddBio'";  
 
  if (@mysql_query($sql)) {  
     echo("Artist Added");  
  } else {  
     echo("<p>Error adding submitted order: " .  
           mysql_error() . "</p>");  
  }  
       
  // next insert the record to Pictures  
  $sql = "INSERT INTO Pictures SET  
      fileSRC='$AddPicture'";  
 
  if (@mysql_query($sql)) {  
     echo("Picture Added");  
  } else {  
     echo("<p>Error adding submitted order: " .  
            mysql_error() . "</p>");  
  }        
}

That should do it!

Targeting A Frame

Doctor,
In a frameset, I’ve created a link to a page that should load in another frame. The link comes from "frame3" and the linked page should appear in "frame2" — but it doesn’t!!!!!!

No matter what I put into the "target" attribute the page still appears in "frame3" thus removing my navigation-bar. I have tried _top, _parent, default, _blank etc. in the "TARGET" field. Nothing seems to work. Help!!!
René

René, I’m sensing some frustration from your use of exclamation marks. Sometimes, as desperate as I might be to finish off some coding, when I feel like bashing my head against the monitor, I know it’s time to ease off the caffeine and go outside, rediscover what sunlight is, and charge up on Vitamin D.

If you want to target a frame from another frame you need to use the target frame’s name. Let’s say we have the following frameset:

<frameset rows="50%,*">   
 <frame name="frame1" src="navigation.html">  
 <frame name="frame2" src="body.html">  
</frameset>

And navigation.html (which is loaded into frame1) has the following link which will open up in frame2:

<a href="somepage.html" target="frame2">click here    
to open the page inside frame2.</a>

Viola!

Lights, Camera, Action!

Doc, I designed some really snazzy rollover/navigation buttons for my Website in Swish and exported them as .swf (flash) files. I just can’t get my HTML editor (Homesite 4.5) to call them out :( I thought:

<a href "main.html">img src"img/main.swf" width="200"    
height="32" alt"" border="0"></a><br>

would do it, but no luck. Now I’m back to boring old .jpgs
Thanks for any advice,
Ryan

Aye-ah! That anchor tag is very mangled. Remember a tag always takes this form:

<tagType attribute=value attribute2=value2 attribute3=value3>

Values that are strings must be enclosed in quotes. For example:

<img src="myImage.jgp" width=100 height=100 border=0 alt="Just an image">

Anyway, that doesn’t really get us any closer to solving the problem. I am happy to admit I’m out of my league on this one. You might want to look into adding actions to your Swish movies. Here’s a tutorial that looks promising — good luck! And don’t forget to ask in the SitePoint Forums if you need quick advice from some pretty handy Swish users.

Including Headers and Footers

Dr. Design,
How can I include a header and footer in an html page?
Thanks,
Winston

Most Web servers support Server Side Includes (SSI). To be able to use SSI in an html page you need to use the file extension .shtml on your Web pages, so that the Web server knows to parse the file and process the include directives. Here is an example of using SSI to include a header and footer from different files:

<!--#include file="header.html" -->   
<p>Some regular old HTML goes here.</p>  
<!--#include file="footer.html" -->

Don’t forget to save the page with the .shtml extension! You can also use SSI include directives in your ASP files. Which reminds me, I saw patient in the clinic two months back with a similar case of the includes. You can read the advice I gave then — hope it helps.

Consulting hours are over, but make sure your questions get answered when the surgery opens again next month!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.