Dr Design – Javascript to PHP

Share this article

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!

Dr. DesignDr. Design
View Author

Dr Design answers design and development questions for SitePoint readers. Drop him a line today!

Share this article
Read Next
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 9 Best WordPress AI Plugins of 2024
Top 9 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
How to Analyze Large Text Datasets with LangChain and Python
How to Analyze Large Text Datasets with LangChain and Python
Matt Nikonorov
6 Techniques for Conditional Rendering in React, with Examples
6 Techniques for Conditional Rendering in React, with Examples
Yemi Ojedapo
Introducing STRICH: Barcode Scanning for Web Apps
Introducing STRICH: Barcode Scanning for Web Apps
Alex Suzuki
Using Nodemon and Watch in Node.js for Live Restarts
Using Nodemon and Watch in Node.js for Live Restarts
Craig Buckler
Task Automation and Debugging with AI-Powered Tools
Task Automation and Debugging with AI-Powered Tools
Timi Omoyeni
Quick Tip: Understanding React Tooltip
Quick Tip: Understanding React Tooltip
Dianne Pena
12 Outstanding AI Tools that Enhance Efficiency & Productivity
12 Outstanding AI Tools that Enhance Efficiency & Productivity
Ilija Sekulov
React Performance Optimization
React Performance Optimization
Blessing Ene Anyebe
Introducing Chatbots and Large Language Models (LLMs)
Introducing Chatbots and Large Language Models (LLMs)
Timi Omoyeni
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Ampere Computing
Scale Your React App with Storybook and Chromatic
Scale Your React App with Storybook and Chromatic
Daine Mawer
10 Tips for Implementing Webflow On-page SEO
10 Tips for Implementing Webflow On-page SEO
Milan Vracar
Create Dynamic Web Experiences with Interactive SVG Animations
Create Dynamic Web Experiences with Interactive SVG Animations
Patricia Egyed
5 React Architecture Best Practices for 2024
5 React Architecture Best Practices for 2024
Sebastian Deutsch
How to Create Animated GIFs from GSAP Animations
How to Create Animated GIFs from GSAP Animations
Paul Scanlon
Aligning Teams for Effective User Onboarding Success
Aligning Teams for Effective User Onboarding Success
Himanshu Sharma
How to use the File System in Node.js
How to use the File System in Node.js
Craig Buckler
Laravel vs CodeIgniter: A Comprehensive Comparison
Laravel vs CodeIgniter: A Comprehensive Comparison
Dianne Pena
Essential Tips and Tricks for Coding HTML Emails
Essential Tips and Tricks for Coding HTML Emails
Rémi Parmentier
How to Create a Sortable and Filterable Table in React
How to Create a Sortable and Filterable Table in React
Ferenc Almasi
WooCommerce vs Wix: Which Is Best for Your Next Online Store
WooCommerce vs Wix: Which Is Best for Your Next Online Store
Priyanka Prajapati
GCC Guide for Ampere Processors
GCC Guide for Ampere Processors
John O’Neill
Get the freshest news and resources for developers, designers and digital creators in your inbox each week