Intro to Cascading Style Sheets (CSS) [top]
Style sheets were invented to increase the functionality and usefulness of visual elements used to layout a design in a user's browser. In practice, its use consists of defining a set of rules that will govern the look and feel of the page. Each rule has two parts:
An example?
p {
font-family: verdana;
font-size: 14px;
color: green;
}
Here is a paragraph that uses the above style. Here is another sentence in the paragraph that uses the above style. Here is yet another sentence in the paragraph that uses the above style.
There's three ways in which CSS styles can be defined:
Inline CSS
Using inline CSS, you can define a style entirely within the appropriate HTML tag, essentially assigning the style to the element as you go. For example, to create the green paragraph above, I wrote the following:
<p style="color: green; font-size: 14px; font-family: verdana;"> Here is a paragraph that ...</p>
Embedded CSS
To embed a style sheet in a Web page, you place your rule set in a style block in the head of the document HTML, like so:
<html>
<head>
<title>My Page</title>
<style type="text/css">
p {
font-family: verdana;
font-size: 14px;
color: green;
}
</style>
</head>
The advantage of this is that you don't have to keep defining the rules for a particular HTML element each time you create it. The rule set is defined at the top of the document and can apply to all instances of the element in the page.
External CSS
External CSS is similar to embedded CSS except that the rule set is moved to a separate file with a ".css" extension and then linked in whatever HTML document needs it. In this case, I could create a CSS file called "test.css" containing the following:
p {
font-family: verdana;
font-size: 14px;
color: green;
}
and then link to it in my HTML page like so:
<html> <head> <title>My Page</title> <link rel="stylesheet" href="../css/test.css" type="text/css" /> </head>
Note that our test.css file does not need the <style type="text/css"></style> tag because by nature of its .css extension, it's assumed to be of CSS content and thus does not need to be delineated in the file as such.
Assigning CSS Rules [top]
As shown above, we can pick an HTML element and assign rules. To override the properties of an existing HTML element (a, b, body, img, p, h1, h2, etc), we simply reference it and define, so to set attributes for our HTML body, we could say something like:
body {
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
font-family: verdana, arial, helvetica, sans-serif;
color: #000;
background-color: #fff;
}
To define how our links will look, we could say:
a {
text-decoration: none; color: #a63;
}
and all our links in the page will have this look and feel.
Another way is to assign a unique ID to a class of rules using the "#" prefix and a unique name:
#mybox {
width: 320px;
height: 240px;
font: 12px Verdana;
border: 1px solid #ccc;
}
Then, to use this class, we assign to the HTML element of our choice, such as a div, using its ID attribute:
<div id="mybox">This text is in a box that is 320 x 240.</div>which would look like this:
To create a general class, we can use the "." prefix and a unique name for our class:
.myfont {
font: 13px Arial, Verdana, Geneva, Helvetica, sans-serif;
color: #369;
font-weight: normal;
text-decoration: none;
}
and then use it as such:
<div class="myfont">This text has properties from the class "myfont".</div> <p>Here is some text that does not have the same properties.<p> <font class="myfont">This text also has properties from the class "myfont".</font>which would look like this:
Here is some text that does not have the same properties.
This text also has properties from the class "myfont".
We can also link classes together to assign properties to elements within another element. For example, here's a class that describes both font and anchor properties:
.myfont1 {
font: 13px Arial;
color: #369;
font-weight: normal;
text-decoration: none;
}
.myfont1 a { text-decoration: underline; color: #a63; }
.myfont1 a:link { text-decoration: underline; color: #a63; }
.myfont1 a:visited { text-decoration: underline; color: #a63; }
.myfont1 a:hover { text-decoration: underline; color: #f00; }
and then use it as such:
<div class="myfont1">Here is some text in a div that uses 13px Arial, a color of #336699 and some <a href="http://www.yahoo.com" target="somePage">link properties</a> associated with rollovers and being visited</div>which would look like this:
CSS In Practice [top]
In practice, we can use CSS to layout sections of our page and to easily give it the look and feel we desire. Here is the favorite sites demo with some CSS applied:
The elements that have been defined for this layout are as follows:
body {
margin: 5px;
font: 13px arial;
color: #000;
background-color: #fff;
}
/* Main div */
.maindiv {
font: 13px arial;
margin: 5px;
padding: 5px;
}
/* Text for title */
.titletext {
font-size: 16px;
font-weight: bold;
}
/* Text for status msg */
.statustext {
color: #900;
font-weight: bold;
}
/* Text for error msg */
.errortext {
color: #f00;
font-weight: bold;
}
/* Text for table */
.tabletext {
font: 11px Arial;
color: #333;
font-weight: normal;
text-decoration: none;
}
.tabletext A { text-decoration: underline; color: #a63; }
.tabletext A:link { text-decoration: underline; color: #a63; }
.tabletext A:visited { text-decoration: underline; color: #a63; }
.tabletext A:hover { text-decoration: underline; color: #f00; }
/* Submit button */
.sbutton {
border: 1px solid #333;
padding: 1px;
font-weight: bold;
font-size: 12px;
background-color: #366;
color: #fff;
text-decoration: none;
}
/* Text box */
.tbox {
font: 11px Arial;
color: #333;
text-decoration: none;
font-weight: normal;
width: 200px;
background-color: #eee;
}
Similarly, we can use CSS to define the boundaries of content areas on the page. One common use is the familiar 3-box layout common to many site designs such as Amazon, in which the navigation is placed in the left, main content in the middle, and extras in the right. We'll apply this same principle to how are favorite sites are displayed:
The elements that have been defined for this layout are as follows:
body {
font: 13px arial;
color: #000;
background-color: #fff;
}
#left {
position: absolute;
top: 0px;
left: 0px;
margin: 20px;
padding: 10px;
border: 1px solid #ccc;
background: #e8e8e8;
width: 120px;
}
#middle {
margin: 20px 190px 20px 190px;
padding: 10px;
border: 1px solid #ccc;
background: #e8e8e8;
}
#right {
position: absolute;
top: 0px;
right: 0px;
margin: 20px;
padding: 10px;
border: 1px solid #ccc;
background: #e8e8e8;
width: 120px;
}
Random CSS Goodies [top]
The @font-face directive in CSS allows to use custom fonts in a web page even if it's not installed on the user's computer.
It's a bit wonky when it comes to IE, but works most everywhere else to great effect. To use @font-face, declare the name
of your font, along with the url to the font file on your server. .otf files will get pretty far when it comes to font formats.
Then assign that font family to a class or element:
<style>
@font-face {
font-family: League-Gothic;
src: url('fonts/League-Gothic.otf');
}
.gogoth {
font-size: 32px;
font-family: League-Gothic;
}
</style>
Here is some text in League-Gothic. Nice!
Another interesting use of basic CSS is rollover menus. In this case, we have a set of links, and when you hover over a specific link, you get a styled dropdown menu with suboptions related to that link.
There are many ways to achieve this. A simple example is to have your main menu presented as an unordered list. Inside each list item is a div that contains the submenu, which is initially hidden by setting its 'display' property to 'none'. Then in your CSS, you trigger the display of the div based upon the hover property of the list item
li:hover div.headdiv {
display: block;
z-index: 2;
}
Note that we set the z-index greater than 0 to make sure the submenu displays on top of whatever content may be behind it.
Introduction to JavaScript [top]
JavaScript is a simple, interpreted programming language with object-oriented capabilities. Although it has the word "Java" in its name, it is not particularly related to the Java programming language developed by Sun. It was actually created by Netscape for use on the client-side in their Navigator browser, and on the server-side in their Enterprise server products. Its popularity now resides mostly on the client-side and it offers dynamic website developers the ability to create interactivity without having to request additional pages from the server. In some ways, it can mimic some of PHP's functionality while functioning solely within the browser, and without the aid of a call to the web server. Also, note that like PHP, JavaScript is case-sensitive, so be careful and be consistent in the naming of your variables and functions. It's commonly used for such tasks as:
Embedding JavaScript In HTML [top]
JavaScript can be embedded pretty much anywhere in your HTML. The main thing is that you need to declare where you're going to start using Javascript, and when you're going to end it, which is done like so:
<script type="text/javascript"> // A double slash means this is a comment // Your JavaScript calls go here </script>such that you can have an HTML page like:
<html> <head> <title>Everybody Do The JavaScript</title> </head> <body> This page has some JavaScript in it. <script type="text/javascript"> // A double slash means this is a comment // Your JavaScript calls go here </script> </body> </html>As far as comments go, everything between // and the end of a line is a comment and will be ignored. For large blocks of text, you can use "/*" to start the comment and "*/" to end it:
<html> <head> <title>Everybody Do The JavaScript</title> </head> <body> This page has some JavaScript in it. <script type="text/javascript"> /* "Now is the time for every good man to come to the aid of his country." I think this is a quote by Nathan Hale but I'm not really sure, so don't quote me (or him) on that. Thanks! */ // Chris, you ignorant jerk - I did, in fact, say it. Piss off! // -Nathan Hale </script> </body> </html>
The Object Model and Write Method [top]
There are a few different objects in the JavaScript hierarchy which constitute what is called the "Document Object Model" (DOM).
The "Window" object represents the top-level browser window. It contains other useful objects, most prominently the "document" object, which is the actual contents inside of the Window. Objects have methods which allow them to affects the contents of that object. We can see what the overall Document Object Model looks like below:

If we want a reference to the contents of the current document, we can code it as either:
window.documentor
documentIf you are referring to the current window, then you have the option of including a reference to the "window" object or ignore it. If you'd like to affect a different window - for example, if you have two windows inside a frameset, or a separate popup window - then you need to include a specific reference to which window you'd like to affect.
An important method of the Document object is the "write" method, which is kind of like "print" statement in PHP, except that the writing is actually done by the JavaScript interpreter in the Web browser on the client's computer, and not by the PHP interpreter on the server. Here's an example:
<script type="text/javascript">
// Here is an example of document.write()
document.write("This sentence was created using JavaScript");
</script>
document.write("<font face=\"verdana\" size=\"3\">");
document.write("<b>This entire document was created using JavaScript</b>");
document.write("</font>");
This is the same as if we had written HTML like:
<font face="verdana" size="3"> <b>This entire document was created using JavaScript</b> </font>You can also give feedback to the user in a popup dialog instead of inside the HTML page. The Window object has a method called "alert" which will create a popup dialog containing whatever text you like:
alert("This has got to be the worst class ever. I hate JavaScript!");
The Concept of a Function in JavaScript [top]
Like most other programming languages, JavaScript supports the concept of the subroutine, which can often be useful if you want to use certain functionality for more general purposes. In JavaScript, this is called a function. For example, our use of the alert command could be re-cast as a function, and the text in alert box could be a variable. In these cases, the function is often positioned in the <HEAD> tag of the HTML.
<html>
<head>
<title>Everybody Do The JavaScript</title>
<script type="text/javascript">
// Show a popup dialog with whatever text you give it
function ShowAlert(myText)
{ alert(myText);
}
</script>
</head>
<body>
This page has some JavaScript in it.
<script type="text/javascript">
// Call the function with various text strings
ShowAlert("Here is the first dialog!");
ShowAlert("Isn't this fun???");
ShowAlert("...not really...");
</script>
</body>
</html>
We don't necessarily need to use JavaScript commands to call JavaScript functions. We can actually embed them as HTML links. The only thing to keep in mind is that, because HTML uses the " character to denote the start and the stop of the actual link, we need to change the delimiter that we use to define our string in JavaScript from a " to a '. Since we already have a ' in our string "Isn't this fun???", we need to escape it using the \ character such that we get 'Isn\'t this fun???':
<html>
<head>
<title>Everybody Do The JavaScript</title>
<script type="text/javascript">
// Show a popup dialog with whatever text you give it
function ShowAlert(myText)
{ alert(myText);
}
</script>
</head>
<body>
<font face="verdana, arial" size="2">
Here is an example of how you can create links to JavaScript functionality.
<p>
<a href="javascript:ShowAlert('Here is the first dialog!');">Show first alert</a><br>
<a href="javascript:ShowAlert('Isn\'t this fun???');">Show second alert</a><br>
<a href="javascript:ShowAlert('...not really...');">Show third alert</a><br>
</font>
</body>
</html>
In this case, the only JavaScript on our page is really the function that we've placed in the HTML HEAD area, but we reference it in the body of HTML using links.
Now alerts can get very annoying but they are very useful for debugging. Fortunately, we have a less intrusive way of printing out the state of our code while executing, and that is console.log
<script type="text/javascript">
// Print to the console
console.log('here is a msg');
</script>
Most modern browsers have Javascript debugging built-in (Chrome's Developer Tools) or as an add-on (Firebug), which allows you to see the output of the console. However, some older browsers (IE6) do not support console.log and will throw an error if invoked, so we can use alert as a fallback:
<script type="text/javascript">
// Print to the console or throw up an alert if not supported
function trace(msg) {
try { console.log(msg) } catch (e) { alert(msg) }
};
</script>
Popup Windows [top]
So now we have the basic background to cover popup windows in JavaScript. The command we're going to exploit is the window.open() command. We'll put it in a function, and we'll pass in some of the parameters used to control it, such as the URL to display, and the height and the width of the popup window.
<html>
<head>
<title>Everybody Do The JavaScript</title>
<script type="text/javascript">
// Show a popup window with whatever url and size you give it
var myPopupWindow = null;
function ShowPopup(url,h,w)
{ myPopupWindow = window.open(url,"myPopupWindow",
"toolbar=no,status=no,menubar=no,location=no,scrollbars=yes,resizable=yes,height="+h+",width="+w);
}
</script>
</head>
<body>
<font face="verdana, arial" size="2">
Here is an example of how you can create popup windows with JavaScript functionality.
<p>
<a href="javascript:ShowPopup('http://www.google.com',600,300);">Show Google in Popup Window</a><br>
<a href="javascript:ShowPopup('http://www.yahoo.com',500,500);">Show Yahoo in Popup Window</a>
</body>
</html>
The window.open() function takes 3 parameters: url, name, and preferences. In the preferences, you can specify whether the new window will have a toolbar, menubar, status, URL location window, scrollbars, the ability to resize, and what its dimensions are. It's good to name your popup window because if your popup has previously been created, then it will simply use that one to show whatever new URL you'd like to show.
Dynamic Element Manipulation [top]
Since we have access to various HTML elements via JavaScript, we can script the contents or style of their various properties. This is one of the core attributes of the "Web 2.0" style, and the built-in function that lets us do most of the magic is:
getElementById()If we assign an id attribute to all page elements that are to be manipulated, we can gain access to them in JavaScript using this function. Consider the case of the class 2 random quote generator, which I have converted to run in JavaScript instead of PHP. By giving an ID to the div element that holds the actual quote, we can manipulate it solely from the client-sde without having to refresh the page or go to the server for another quote. The underlying concept is exactly the same - only the actual syntax of the programming is different. In order to show the quote, we exploit the "innerHTML" property of the HTML div tag, and gain access using getElementById():
var quotes = new Array(15);
quotes[0] = '"I feel ... "<br>- Stephen Bishop';
...
// Show the selected quote
function ShowQuote(n)
{ document.getElementById("quotediv").innerHTML = quotes[n];
}
...
<div id="quotediv" style="margin: 10px 0px 0px 0px; color: #900;">
</div>
Dynamic Div Display [top]
Instead of dynamically populating the div, we can script the visibility of the div and dynamically manipulate it. In this case, I have a few paragraphs along with a hidden paragraph that has its CSS display property set to none. By toggling the value of this property via user interaction, the user has the option of opening or closing this piece of content. This also introduces a new concept that's vital to Javascript: events (more this to come):
<p><a href="#" onclick="javascript:document.getElementById('giantsrule').style.display = 'block';">Show the hidden div</a></p>
<p id="giantsrule" style="display:none;">
<b>Don't Count Out the Giants!!!</b> ... <br/><br/>
<a href="#" onclick="document.getElementById('giantsrule').style.display = 'none';">[-] Close</a>
</p>
Interacting with HTML Forms [top]
One of the great things about JavaScript is that it gives you access to any HTML form widget, as long as you have given the form a name. The document object contains an HTML form object, which contains HTML widget objects, which have values that can either be read or set. So if we had an HTML form called "myForm", and an HTML text widget called "myTextField", we could get to its value using the following variable:
document.myForm.myTextField.valueThus, we could either read its current value, or we could set it, like in the following example:
<html>
<head>
<title>Everybody Do The JavaScript</title>
<script type="text/javascript">
// Fill a text widget with whatever text you give it
function ShowText(myText)
{ document.myForm.myTextField.value = myText;
}
</script>
</head>
<body>
<font face="verdana, arial" size="2">
Here is an example of how you can access HTML form widgets with JavaScript functionality.
<p>
<form name="myForm">
<input type="text" name="myTextField" value="">
</form>
<p>
<a href="javascript:ShowText('blue');">Put "blue" in text field</a><br>
<a href="javascript:ShowText('red');">Put "red" in text field</a><br>
<a href="javascript:ShowText('');">Clear the text field</a><br>
</body>
</html>
For the SELECT HTML widget, you can get its value based upon the selected index. In this case, we don't know the value exactly, but we can find out which index was selected. Indexes start at 0:
document.myForm.mySelectWidget.selectedIndexIn the JavaScript object model, widgets can sometimes have predefined methods for the purpose of catching events associated with them. One of the most common is "onChange()" which you can use to call a particular function whenever a widget has been changed. For Select widgets, this is usually detected when an index that is different from the current one has been selected. For text fields, it's usually when the user clicks outside of the current text field. The "onChange()" method can actually be defined when you code the widget like so:
<select name="mySelectWidget" onChange="GetSelectValue();">or
<textarea name="textarea1" cols=40 rows=8 onChange="MirrorThis();"></textarea>In this case, it is assumed that we have defined two JavaScript functions called "GetSelectValue()" and "MirrorThis()" somewhere on our page.
OnClick() is also a very common method for capturing user events. Try it on links, buttons, checkboxes, etc:
<input type="radio" name="myRadioName" onClick="GetRadioValue('#ffffff');">White
<form>
<input id="colorField" type="text">
</form>
<p>
<a href="#" onclick="document.getElementById('colorField').value='blue';">Put "blue" in text field</a><br>
<a href="#" onclick="document.getElementById('colorField').value='red';">Put "red" in text field</a><br>
<a href="#" onclick="document.getElementById('colorField').value='';">Clear the text field</a><br>
One of the most common uses of JavaScript with regards to forms is to perform error checking on the inputted data. Previously, we had done this on the PHP, in which the user submitted the form, and on the server, we checked these values and returned a page with error messages if there was a problem. In this case, we can check them using JavaScript before they are ever sent to the server, and pop-up an alert if there is a problem.
<script type="text/javascript">
// Check form input before we submit
function CheckValues()
{ if ((document.myForm.firstname.value != "") && (document.myForm.lastname.value != ""))
{ // We have good submission
return true;
}
else
{ // We have one or two empty fields
alert("Please enter a valid firstname and lastname, you punk!");
return false;
}
}
</script>
Alerts can be pretty annoying when it comes to user interface design, so instead, we can handle error-checking much the same way we did in PHP by showing bright red error messages. To do this in Javascript, we can pre-define the error msgs in HTML <div> tags and then conditionally hide or show them based upon user input.
<script type="text/javascript">
// Check form input before we submit
function CheckValues()
{ var haveErrors = 0;
var firstname = document.myForm.firstname.value;
firstname = TrimValue(firstname);
var lastname = document.myForm.lastname.value;
lastname = TrimValue(lastname);
if (firstname == "")
{ haveErrors = 1;
document.getElementById("errfirstname").style.display = "block";
}
else
{ document.getElementById("errfirstname").style.display = "none";
}
if (lastname == "")
{ haveErrors = 1;
document.getElementById("errlastname").style.display = "block";
}
else
{ document.getElementById("errlastname").style.display = "none";
}
if (haveErrors)
return false;
else
return true;
}
function TrimValue(myStr)
{ myStr = myStr.replace(/^\s+/, "");
myStr = myStr.replace(/\s+$/, "");
return(myStr);
}
</script>
Embedded vs. External JavaScript [top]
Just as we saw with CSS, we can hsave JavaScript embedded in the page where it is used, or we can move it to an external file and simply link to it. This is great if we have a variety of functions and code that we'd like to have handy in all of our pages. Applied to the error-checking example above, I could create a JS file called "dwd.js" containing the following:
// Check form input before we submit
function CheckValues()
{ var haveErrors = 0;
var firstname = document.myForm.firstname.value;
firstname = TrimValue(firstname);
var lastname = document.myForm.lastname.value;
lastname = TrimValue(lastname);
if (firstname == "")
{ haveErrors = 1;
document.getElementById("errfirstname").style.display = "block";
}
else
{ document.getElementById("errfirstname").style.display = "none";
}
if (lastname == "")
{ haveErrors = 1;
document.getElementById("errlastname").style.display = "block";
}
else
{ document.getElementById("errlastname").style.display = "none";
}
if (haveErrors)
return false;
else
return true;
}
function TrimValue(myStr)
{ myStr = myStr.replace(/^\s+/, "");
myStr = myStr.replace(/\s+$/, "");
return(myStr);
}
and then link to it in my HTML page like so:
<html> <head> <title>More JavaScript w/Form Checking and External JS</title> <script src="../js/dwd.js" type="text/javascript"></script> </head>Note that our dwd.js file does not need the <script ... > tag because by nature of its declaration in our HTML pages, it's assumed to be of JavaScript content and thus does not need to be delineated in the file as such.
Javascript Frameworks and Intro to jQuery [top]
[From the Wikipedia] "JavaScript frameworks are libraries of pre-written JavaScript controls which allow for easier development of JavaScript-based applications, especially for AJAX and other web-centric technologies. With the expanded demands for JavaScript, an easier means for programmers to develop such dynamic interfaces was needed. Thus, JavaScript libraries such as Prototype, script.aculo.us, and JQuery and JavaScript widget libraries such as Ext and Dojo Toolkit were developed, allowing for developers to concentrate more upon more distinctive applications of AJAX."
We'll get into the AJAX segment of Javascript frameworks a bit later, but the main thing you need to know for now is that a framework like jQuery can easily simplify the manipulation of the DOM and any events associated with these elements. In effect, the majority of the functionality you've seen so far can be created with greater ease using jQuery.
The jQuery library exists as a single JavaScript file, and can be included within any web page by using something similar to the following markup:<script src="/path/to/jquery.js" type="text/javascript"></script>For greater ease, many web entities provide url access to the most current version of jQuery such that you don't even need to host it:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>For selection of a DOM element, it's good to give the target a unique id, or a class if you want to target multiple items:
<input type="text" id="mytext" size="30" value="Some text in a field" /> <a href="#" id="asc" class="sortlink">Sort Asc</a> | <a href="#" id="desc" class="sortlink">Sort Desc</a>Then in your Javascript, you can bind functionality to their associated events, like if they're clicked. This functionality takes the form of a callback function, which you can specify right in the code that defines the event:
<script type="text/javascript">
// Put all jQuery events inside $(document).ready() to make sure jQuery has been loaded
$(document).ready(function()
{
// click event for the element with id 'mylink'
$("#mylink").click(
function() {
console.log('The element with id mylink was clicked');
}
);
// click event for all elements that have been given the class 'sortlink'
$(".sortlink").click(
function() {
console.log('An element with class sortlink was clicked');
}
);
});
</script>
Although not its strongpoint, jQuery has some nice built-in functions for visual effects:
show( )Displays each of the set of matched elements if they are hidden.
show( speed, callback )Show all matched elements using a graceful animation and firing an optional callback after completion.
hide( )Hides each of the set of matched elements if they are shown.
hide( speed, callback )Hide all matched elements using a graceful animation and firing an optional callback after completion.
toggle( )Toggles displaying each of the set of matched elements.
slideDown( speed, callback )Reveal all matched elements by adjusting their height and firing an optional callback after completion.
slideUp( speed, callback )Hide all matched elements by adjusting their height and firing an optional callback after completion.
slideToggle( speed, callback )Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.
fadeIn( speed, callback )Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.
fadeOut( speed, callback )Fade out all matched elements by adjusting their opacity and firing an optional callback after completion.
fadeTo( speed, opacity, callback )Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.
PHP Writes JavaScript [top]
It seems strange, but at this point, it is now pretty trivial to get a server-side script to write client-side code. We have already seen how JavaScript can be embedded in HTML, and how PHP can write HTML, so we can get PHP to write HTML and JavaScript at the same time.
And if we can get PHP to write JavaScript, this also means we can write JavaScript values using data from our database. Here's our random quote generator, but redone with data that comes from a table in our database, instead of a static array in either JavaScript or PHP:
# Get the number of quotes
$numQuotes = 0;
$SqlStatement = "SELECT count(id) FROM quote ";
$result = mysql_query($SqlStatement,$connection);
if (!$result) die("Error " . mysql_errno() . " : " . mysql_error());
if ($row = mysql_fetch_array($result,MYSQL_NUM))
{ $numQuotes = $row[0];
}
# Print our JavaScript
?>
<script type="text/javascript">
var quotes = Array(<?=$numQuotes?>);
<?
# Now populate the JS array with values from DB
$counter = 0;
$SqlStatement = "SELECT name FROM quote ORDER BY id";
$result = mysql_query($SqlStatement,$connection);
if (!$result) die("Error " . mysql_errno() . " : " . mysql_error());
while ($row = mysql_fetch_array($result,MYSQL_NUM))
{ $quote = $row[0];
$quote = str_replace("'", "\'", $quote); # Escape any single quotes in our text
print "quotes[$counter] = '$quote'; \n";
$counter++;
}
?>
//-->
</script>
Related Resources [top]