This is an old revision of the document!
In this activity you'll learn to use Javascript to
form.php
<?php include('database.php'); include('header.php'); include('menu.php'); // get list of heroes $query = "SELECT * FROM heroes"; $args = array(); $hrslt = $pdo->prepare($query); $hrslt->execute($args); // get list of movies $query = "SELECT movie FROM appearances GROUP BY movie"; $args = array(); $mrslt = $pdo->prepare($query); $mrslt->execute($args); ?> <main> <form name="add_hero" action="process_form.php" method="post"> <fieldset> <legend>Add Hero</legend> <ul> <li> <label>Alias:</label> <input type="text" name="alias" size="30" maxlength="50" hint="Iron Man"> </li> <li> <label>Identity:</label> <input type="text" name="identity" size="30" maxlength="50" hint="Tony Stark"> </li> <li> <label>Side:</label> <ul> <li><input type="radio" name="side" value="Hero" checked> Hero</li> <li><input type="radio" name="side" value="Villain"> Villain</li> </ul> </li> <li> <label>First Appearance:</label> <input type="number" name="year"> </li> <li> <label>Source of Power:</label> <select name="power"> <option value="Skill">Skill</option> <option value="Biological">Biological</option> <option value="Magic">Magic</option> <option value="Technology">Technology</option> <option value="Mutant">Mutant</option> </select> </li> </ul> <input type="submit" name="submit" value="Add / Update Hero"> </fieldset> </form> <form name="add_appearances" action="process_form.php" method="post"> <fieldset> <legend>Add Appearances</legend> <ul> <li> <label>Hero</label> <select name="alias"> <?php // display list of heroes while($row = $hrslt->fetch()) { ?> <option value="<?php echo $row['alias']; ?>"><?php echo $row['alias']; ?></option> <?php } ?> </select> </li> <li> <label>Movie</label> <ul> <?php // display list of movies while($row = $mrslt->fetch()) { ?> <li><input type="checkbox" name="movie[]" value="<?php echo $row['movie']; ?>" id=""> <?php echo $row['movie']; ?></li> <?php } ?> <li><input type="checkbox" name="movie[]" value="new" id=""> <input type="text" name="new_movie"></li> </ul> </li> </ul> <input type="submit" name="submit" value="Add Appearance"> <input type="submit" name="submit" value="Delete Appearances"> </fieldset> </form> </main> <?php include('footer.php'); ?>
process_form.php
<?php include('header.php'); include('menu.php'); include('database.php'); // check which form switch ($_POST['submit']) { case 'Add / Update Hero': // check whether hero already exists $hquery = "SELECT * FROM heroes WHERE alias=?"; $hargs = array($_POST['alias']); $hrslt = $pdo->prepare($hquery); $hrslt->execute($hargs); if($row = $hrslt->fetch()) { // the hero exists $query = "UPDATE heroes SET identity=?, hero_villain=?, first_appeared=?, power=? WHERE alias=?"; $args = array($_POST['identity'], $_POST['side'], $_POST['year'], $_POST['power'], $_POST['alias']); $rslt = $pdo->prepare($query); if($rslt->execute($args)) { $message = "{$_POST['alias']} was updated successfully."; } else { $message = "There was a problem updating {$_POST['alias']}."; } } else { $query = "INSERT INTO `heroes` (`alias`, `identity`, `hero_villain`, `first_appeared`, `power`) VALUES (?,?,?,?,?)"; $args = array($_POST['alias'], $_POST['identity'], $_POST['side'], $_POST['year'], $_POST['power']); $rslt = $pdo->prepare($query); if ($rslt->execute($args)) { $message = "{$_POST['alias']} was inserted successfully."; } else { $message = "There was a problem inserting {$_POST['alias']}."; } } break; case 'Add Appearance': $args = array(); foreach($_POST['movie'] as $movie) { if ($movie == 'new') { array_push($args, $_POST['alias'], $_POST['new_movie']); } else { error_log($movie); // check if it exists already $mquery = "SELECT * FROM appearances WHERE alias=? AND movie=?"; $margs = array($_POST['alias'], $movie); $rslt = $pdo->prepare($mquery); $rslt->execute($margs); if (!$row = $rslt->fetch()) { array_push($args, $_POST['alias'], $movie); } } } error_log(print_r($args, 1)); $movies = count($args)/2; if ($movies > 0) { $values = str_repeat('(?,?), ', $movies-1) . '(?,?)'; $query = "INSERT INTO appearances (alias, movie) VALUES $values"; error_log("MURRAY: $query " . print_r($args, 1)); $rslt = $pdo->prepare($query); if ($rslt->execute($args)) { $message = "$movies appearances were inserted successfully."; } else { $message = "There was a problem inserting $movies appearances."; } } else { $checked = count($_POST['movie']); $message = "All $checked appearances are already in the database."; } break; case 'Delete Appearances': $movies = count($_POST['movie']); $values = str_repeat('?,', $movies-1) . '?'; $query = "DELETE FROM appearances WHERE alias=? AND movie IN ($values)"; $args = array($_POST['alias']); foreach($_POST['movie'] as $movie) { array_push($args, $movie); } error_log($query . print_r($args, 1)); $rslt = $pdo->prepare($query); if ($rslt->execute($args)) { $message = "$movies appearances were deleted successfully."; } else { $message = "There was a problem deleting $movies appearances"; } break; default: break; } ?> <main> <p><?php echo $message; ?></p> </main> <?php include('footer.php'); ?>
style.css
ol { color: blue; } ol ol { font-weight: 700; } ul { list-style-type: none; } td, th { border-width: 1px; border-style: solid; } td { padding: 10px; } table { border-collapse: collapse; } header { background-color:indianred; border:darkred solid 2px; height: 100px; position: absolute; left: 16%; right: 0px; top: 0px; } nav { background-color: burlywood; border:yellow solid 2px; position: fixed; top: 0px; bottom: 0px; width: 16%; left: 0px; } main { background-color: lightgree; border: darkgreen solid 2px; position: absolute; top: 100px; left: 16%; right: 0px; bottom: 80px; overflow: scroll; padding: 20px; } footer { background-color: lightskyblue; border: darkblue solid 2px; position: absolute; bottom: 0px; height: 80px; left: 16%; right: 0px; } .content { background-color:coral; border:orangered solid 2px; height: 400px; padding: 40px; margin: 20px; display: inline-block; width: 300px; } img { float: left; max-height: 250px; border: solid 2px green; margin: 20px 20px 20px 0px; padding: 10px; border-radius: 30px; } #album { display: flex; justify-content:space-between; flex-wrap: wrap; } video { max-height: 250px; float: right; clear: left; margin: 20px 0px 20px 20px; padding: 10px; } audio { margin: 20px 20px 20px 0px; padding: 10px 10px 10px 0px; } input[type=button] { display: block; } figcaption { display: block; text-align: center; font-family: 'Arial', sans-serif; color: green; } label { display: inline-block; width: 10em; text-align: right; } input[type=checkbox], input[type=radio] { margin-left: 11em; } input[type=text], input[type=number], select { margin-left: 1em; } input[name=new_movie] { margin-left: 0em; }
include
lines and html code to the top of 'form.php'.<?php include('database.php'); // check which form switch ($_POST['submit']) { case 'Add / Update Hero': // check whether hero already exists $hquery = "SELECT * FROM heroes WHERE alias=?"; $hargs = array($_POST['alias']); $hrslt = $pdo->prepare($hquery); $hrslt->execute($hargs); if($row = $hrslt->fetch()) { // the hero exists $query = "UPDATE heroes SET identity=?, hero_villain=?, first_appeared=?, power=? WHERE alias=?"; $args = array($_POST['identity'], $_POST['side'], $_POST['year'], $_POST['power'], $_POST['alias']); $rslt = $pdo->prepare($query); if($rslt->execute($args)) { $message = "{$_POST['alias']} was updated successfully."; } else { $message = "There was a problem updating {$_POST['alias']}."; } } else { $query = "INSERT INTO `heroes` (`alias`, `identity`, `hero_villain`, `first_appeared`, `power`) VALUES (?,?,?,?,?)"; $args = array($_POST['alias'], $_POST['identity'], $_POST['side'], $_POST['year'], $_POST['power']); $rslt = $pdo->prepare($query); if ($rslt->execute($args)) { $message = "{$_POST['alias']} was inserted successfully."; } else { $message = "There was a problem inserting {$_POST['alias']}."; } } break; case 'Add Appearance': $args = array(); foreach($_POST['movie'] as $movie) { if ($movie == 'new') { array_push($args, $_POST['alias'], $_POST['new_movie']); } else { error_log($movie); // check if it exists already $mquery = "SELECT * FROM appearances WHERE alias=? AND movie=?"; $margs = array($_POST['alias'], $movie); $rslt = $pdo->prepare($mquery); $rslt->execute($margs); if (!$row = $rslt->fetch()) { array_push($args, $_POST['alias'], $movie); } } } error_log(print_r($args, 1)); $movies = count($args)/2; if ($movies > 0) { $values = str_repeat('(?,?), ', $movies-1) . '(?,?)'; $query = "INSERT INTO appearances (alias, movie) VALUES $values"; error_log("MURRAY: $query " . print_r($args, 1)); $rslt = $pdo->prepare($query); if ($rslt->execute($args)) { $message = "$movies appearances were inserted successfully."; } else { $message = "There was a problem inserting $movies appearances."; } } else { $checked = count($_POST['movie']); $message = "All $checked appearances are already in the database."; } break; case 'Delete Appearances': $movies = count($_POST['movie']); $values = str_repeat('?,', $movies-1) . '?'; $query = "DELETE FROM appearances WHERE alias=? AND movie IN ($values)"; $args = array($_POST['alias']); foreach($_POST['movie'] as $movie) { array_push($args, $movie); } error_log($query . print_r($args, 1)); $rslt = $pdo->prepare($query); if ($rslt->execute($args)) { $message = "$movies appearances were deleted successfully."; } else { $message = "There was a problem deleting $movies appearances"; } break; default: break; } include('header.php'); include('menu.php'); // get list of heroes $query = "SELECT * FROM heroes"; $args = array(); $hrslt = $pdo->prepare($query); $hrslt->execute($args); // get list of movies $query = "SELECT movie FROM appearances GROUP BY movie"; $args = array(); $mrslt = $pdo->prepare($query); $mrslt->execute($args); ?> <main> <form name="add_hero" action="process_form.php" method="post"> <fieldset> <legend>Add Hero</legend> <ul> <li> <label>Alias:</label> <input type="text" name="alias" size="30" maxlength="50" hint="Iron Man"> </li> <li> <label>Identity:</label> <input type="text" name="identity" size="30" maxlength="50" hint="Tony Stark"> </li> <li> <label>Side:</label> <ul> <li><input type="radio" name="side" value="Hero" checked> Hero</li> <li><input type="radio" name="side" value="Villain"> Villain</li> </ul> </li> <li> <label>First Appearance:</label> <input type="number" name="year"> </li> <li> <label>Source of Power:</label> <select name="power"> <option value="Skill">Skill</option> <option value="Biological">Biological</option> <option value="Magic">Magic</option> <option value="Technology">Technology</option> <option value="Mutant">Mutant</option> </select> </li> </ul> <input type="submit" name="submit" value="Add / Update Hero"> </fieldset> </form> <form name="add_appearances" action="process_form.php" method="post"> <fieldset> <legend>Add Appearances</legend> <ul> <li> <label>Hero</label> <select name="alias"> <?php // display list of heroes while($row = $hrslt->fetch()) { ?> <option value="<?php echo $row['alias']; ?>"><?php echo $row['alias']; ?></option> <?php } ?> </select> </li> <li> <label>Movie</label> <ul> <?php // display list of movies while($row = $mrslt->fetch()) { ?> <li><input type="checkbox" name="movie[]" value="<?php echo $row['movie']; ?>" id=""> <?php echo $row['movie']; ?></li> <?php } ?> <li><input type="checkbox" name="movie[]" value="new" id=""> <input type="text" name="new_movie"></li> </ul> </li> </ul> <input type="submit" name="submit" value="Add Appearance"> <input type="submit" name="submit" value="Delete Appearances"> </fieldset> </form> </main> <?php include('footer.php'); ?>
action
in each form to 'form.php'.<form name="add_hero" action="form.php" method="post">
<form name="add_appearances" action="form.php" method="post">
<main>
.<div id="status"> <p><?php echo $message; ?></p> </div>
#status { background-color: rgb(238, 157, 157); border: darkred 1px solid; color: darkred; margin-bottom: 20px; padding-left: 20px; }
$page = "form"; include('header.php');
window.onload
.window.onload = function () { }
window.onload = function () { var status = document.getElementById('status'); }
setTimeout
to wait 10s before running the function.setTimeout(function () { }, 10000);
{}
.div
from the page. {}
.status.style.display = 'none';
#status { background-color: rgb(238, 157, 157); border: darkred 1px solid; color: darkred; margin-bottom: 20px; padding-left: 20px; display: none; }
window.onload = function () { var status = document.getElementById('status'); if (status.firstElementChild.innerHTML != '') { status.style.display = 'block'; } setTimeout(function () { status.style.display = 'none'; }, 10000); }
<p>
element (the firstChildElement
of 'status'), and if so, sets the display to 'block'.<input type="button" name="submit" value="Add / Update Hero">
<input type="button" name="submit" value="Add Appearance"> <input type="button" name="submit" value="Delete Appearances">
<input type="button" name="submit" value="Add / Update Hero" onclick="verifyAddHero()">
<input type="button" name="submit" value="Add Appearance" onclick="verifyAddAppearance()"> <input type="button" name="submit" value="Delete Appearances" onclick="verifyDeleteAppearance()">
<label>Alias:<span class="required">*</span></label>
<label>Identity:<span class="required">*</span></label>
<label>Side:<span class="required">*</span></label>
<label>First Appearance:<span class="required">*</span></label>
<label>Source of Power:<span class="required">*</span></label>
.required { color: red; vertical-align: super; }
vertical-align: super
is the CSS equivalent of the <sup>
tag to make the asterisk superscript.function verifyAddHero() { }
message = ""; if (document.getElementsByName('alias')[0].value == "") { message += "The alias is required. "; } console.log(message);
document.getElementsByName('alias')
is a list of all elements named 'alias'.[0]
.message
variable first, then add a message to it if necessary.console.log(message);
will display the message in the console so you can see the result now. We'll add the message to the 'status' block later.if (document.getElementsByName('alias')[0].innerHTML == "") { message += "The alias is required. "; } if (document.getElementsByName('identity')[0].innerHTML == "") { message += "The identity is required. "; } console.log(message);
document.getElementsByName('year')[0]
year = document.getElementsByName('year')[0].value;
""
for the same command ('year'), so we have a problem.document.getElementsByName('year')[0].value == ""
==
is a comparison test, which returns 'True' if the expressions on either side are the same and 'False' otherwise. So this statement means 'the year is empty.'year.length
.length
doesn't count the number of elements in an array. It counts the number of characters in text or digits in a string.year.length == 4
!year.length == 4
year.length == 4
, this takes the opposite of year.length
and compares it to 4. ()
!(year.length == 4)
||
in Javascript. The final expression will look like this.if ((year == "") || !(year.length == 4))
()
around the first expression, keeping the two parts consistent helps reduce confusion. &&
. We could say the above as 'if the entered value is NOT BOTH a number AND 4 digits long', which we would write as if (!(year == "") && (year.length == 4))
.var year = document.getElementsByName('year')[0].value; if ((year == "") || !(year.length == 4)) { message += "The first appearance is required and must be a 4-digit year. "; }
var status = document.getElementById('status'); if (message == "") { console.log('ready to submit'); } else { status.firstElementChild.innerHTML = message; status.style.display = 'block'; }
document.getElementsByName'add_hero')[0].submit()
<input type="button" name="formSubmit" value="Add / Update Hero" onclick="verifyAddHero()">
<input type="button" name="formSubmit" value="Add Appearance" onclick="verifyAddAppearance()"> <input type="button" name="formSubmit" value="Delete Appearances" onclick="verifyDeleteAppearance()">
switch ($_POST['formSubmit']) {
console.log('ready to submit');
in 'form.js' with the submit command you tested in the console.var status = document.getElementById('status'); if (message == "") { document.getElementsByName('add_hero')[0].submit(); } else { status.firstElementChild.innerHTML = message; status.style.display = 'block'; }
function verifyAddAppearance() { message = ""; }
<label>Hero</label> <select name="alias"> <option value=""></option> <?php // display list of heroes while($row = $hrslt->fetch()) { ?> <option value="<?php echo $row['alias']; ?>"><?php echo $row['alias']; ?></option> <?php } ?> </select>
alias = document.getElementsByName('alias')[1].value;
[1]
.alias == ""
.function verifyAddAppearance() { var message = ""; var alias = document.getElementsByName('alias')[1].value; if (alias == "") { message += "The Hero is required. "; } }
var movie = document.getElementsByName('movie[]')[0];
in the console you'll see that it is 'undefined', so we need to find another way.document.getElementById('movieList').getElementsByTagName('input')[1]
<input id="" type="checkbox" name="movie[]" value="Iron Man">
element shown in the console.document.getElementById('movieList').getElementsByTagName('input')[1].checked
for (n = 0; n < movieList.length; n++) { }
n < movieList.length
will do this) AND that the movie isn't checked, which we can test with !movieList[n].checked
).while((n < movieList.length) && (!movieList[n].checked)) { n++; }
var message = ""; var noAppearance = 0;
while((n < movieList.length) && (!movieList[n].checked)) { noAppearance++; n++; }
if (noAppearance == movieList.length) { message += "You need to add at least one movie. "; }
movieList[movieList.length-2].checked
movieList[movieList.length-1].value
and we only need a message if both the checkbox is checked AND the name field is blank. So our code needs to be as follows.if ((movieList[movieList.length-2].checked) && (movieList[movieList.length-1].value == "")) { message += "If you check the last box, you need to name the movie."; }
var status = document.getElementById('status'); if (message == "") { console.log('ready to submit'); } else { status.firstElementChild.innerHTML = message; status.style.display = 'block'; }
function verifyAppearance() { var message = ""; var noAppearance = 0; var alias = document.getElementsByName('alias')[1].value; if (alias == "") { message += "The Hero is required. "; } var movieList = document.getElementById('movieList').getElementsByTagName('input'); var n = 0; while((n < movieList.length) && (!movieList[n].checked)) { console.log(n); noAppearance++; n++; } console.log(noAppearance); if (noAppearance == movieList.length) { message += "You need to add at least one movie. "; } if ((movieList[movieList.length-2].checked) && (movieList[movieList.length-1].value == "")) { message += "If you check the last box, you need to name the movie."; } console.log(message); }
function verifyAddAppearance() { // check form data verifyAppearance(); // take action - display message or submit var status = document.getElementById('status'); if (message == "") { console.log('ready to submit'); } else { status.firstElementChild.innerHTML = message; status.style.display = 'block'; } }
return(message);
var message = verifyAppearance();
function verifyDeleteAppearance() { // check form data var message = verifyAppearance(); // take action - display message or submit var status = document.getElementById('status'); if (message == "") { console.log('ready to submit'); } else { status.firstElementChild.innerHTML = message; status.style.display = 'block'; } }
movieList[movieList.length-2].checked = false;
// check form data var movieList = document.getElementById('movieList').getElementsByTagName('input'); var message = verifyAppearance(movieList);
function verifyAppearance(movieList) {
// uncheck 'new' checkbox movieList[movieList.length-2].checked = false;
document.getElementsByName('add_appearance')[0].submit();
document.getElementsByName('add_appearance')[0].submit();