'OnLoad' Attribute Activates CGI Script
Note: The introduction article, "Running a CGI Program On Page Load," contains numerous examples for automatically running a script when a page loads and has links to several different methods of implementing those features for your website.
OnLoad Activation of CGI Script
The onLoad attribute in the BODY tag can be used to automatically run a CGI program when a web page has loaded. The onLoad attribute runs some JavaScript code which runs the CGI script.
The OnLoad Attribute
Here is an example onLoad attribute in the BODY tag to run some JavaScript when the web page completes loading:
<body onload="myJavaScriptFunction()">
The JavaScript
This JavaScript contains a function myJavaScriptFunction() to be called with the onLoad attribute in the above example:
<script type="text/javascript" language="JavaScript"><!-- function myJavaScriptFunction() { var myImage = new Image(); myImage.src = "/cgi-bin/image.cgi"; } //--></script>
Put the JavaScript into the HEAD area of the web page source code.
The JavaScript creates an image object. Then it retrieves the image for that object. Instead of retrieving the image directly from an image file, in this case the image is retrieved from a CGI script.
Change the URL between the quotation marks so it is the correct URL of the script that will return an image to the browser.
The CGI Program
Here is an example CGI script that may be used:
#!/usr/bin/perl use strict; # # script can do other stuff here # # Put the image file to be sent to the browser # in the same directory where this script is # installed. Put the image file's name between # the quotes on the next line. my $image = "image.gif"; open R,"<$image"; binmode R; print "Content-type: image/*\n\n"; binmode STDOUT; while(<R>) { print $_; } close R;
Verify the first line of the script correctly reflects the location of perl on your server.
As with other Perl CGI scripts, do all editing with a plain text word processor like NotePad or TextEdit, and up/download the file as plain text, not binary. Verify the script file on the server has 755 permissions.
Testing
To test the script, use its URL in an image tag and see if the image shows up. Example:
<img src="/cgi-bin/image.cgi" />
If you've used the correct URL and the image doesn't display on your page, try pasting the script's complete http://... URL into your browser's address bar to see any errors that might result from running the script. Example URL:
http://example.com/cgi-bin/image.cgi
See the WillMaster.com "Frequenty Asked Questions" support page if the script runs with errors.
Will Bontrager