COMP3322 MODERN TECHNOLOGIES ON WORLD WIDE WEB
Workshop 3: PHP, JavaScript and AJAX
Overview
In this workshop, we will develop a simple web-based course attendance system, with which we can maintain an attendance list. As shown in Fig. 1, each attendance entry includes the attendance status (PRESENT or ABSENT), student name, student major, course code, and date.
Fig. 1
We will practice loading the list from the database and toggling between the PRESENT status and the ABSENT status, as well as adding a new student in the attendance system. We will also implement a few buttons to decide the (selected) entries to be displayed. For example, when “BBA” is typed into the textbox above “Filter by Major” button and the button is pressed, the filtered result will be shown up as in Fig. 2.
Fig. 2 Fig. 3
When “COMP3322” is typed into the textbox above “Filter by Course” button and the button is pressed, the filtered result will be shown up as in Fig. 3. When a student’s information is
typed in the textboxes below “Please fill in the following attributes for adding a new student in the system (All field must be filled)” and then press the button “Add a new student”, the newly added student will be displayed, as shows up in Fig. 4 & 5.
Note that a “Show All” button is displayed in Fig. 2 and Fig. 3, and when it is clicked, the page view goes back to Fig. 1.
Fig. 4
When the “Add a student” button is clicked
The newly added student will be displayed on the list
Fig. 5
These functionalities will be implemented through server-side implementation (PHP) and the client-side implementation (HTML, JavaScript, AJAX). We adopt MySQL as the back-end database server to store the attendance information.
Task 1: Prepare the database
Step1: Get your MySQL account, if you do not have one, at https://intranet.cs.hku.hk/common/mysqlacct/register.php (Login with your CS account and password after clicking the link). It takes up to one working day for CS technical office to activate your account.
Please use a password for the MySQL account which is different from your CS account password or HKU Portal account password.
Step2: Go to phpMyAdmin: https://i.cs.hku.hk/phpmyadmin/index.php. Type your username and password as registered in Step 1. Select the server as sophia. Select the database which its name is the same as your username.
Step3: Click the SQL button and type the following SQL statements to create a new table and insert new records into the table.
create table attendancelist (id int not null primary key auto_increment, studentname varchar(256), major varchar(256), course varchar(256), coursedate DATE, attendOrNot varchar(7) not null default ‘PRESENT’);
insert into attendancelist values(1,’Alice’, ‘BEng’, ‘COMP3322’, ‘2018-10-15’, ‘PRESENT’); insert into attendancelist values(2,’Bob’, ‘BEcon’, ‘COMP3327’, ‘2018-10-16’, ‘PRESENT’); insert into attendancelist values(3,’Charlie’, ‘BBA’, ‘COMP3329’, ‘2018-10-11’, ‘PRESENT’); insert into attendancelist values(4,’Dave’, ‘BBA’, ‘COMP3322’, ‘2018-10-12’, ‘PRESENT’); insert into attendancelist values(5,’Eve’, ‘BJ’, ‘COMP3403’, ‘2018-10-15’, ‘PRESENT’); insert into attendancelist values(6,’Issac’, ‘BEng’, ‘COMP3403’, ‘2018-10-16’, ‘PRESENT’);
Task 2: Load entries from the database
Download the materials from Moodle- “workshop3_2020.zip”. Unzip it and you will find all four files we need in this workshop.
Open index_WS3.html with a text editor. You will see it contains the following HTML content:
Course Attendance System
Please fill in the following attributes for adding a new student in the system (All field must be filled)
Task 2.1: Implement client-side code for loading all entries
When the page is loaded or the “Show All” button (on the page view as in Fig. 1) is clicked, the showAll() function is invoked to load and display all the attendance entries from the attendanceList table in the database, using AJAX.
Step 1: In index_WS3.html, identify the events that initiate the AJAX communication and implement corresponding event handlers as follows:
1. When the
2. When
is clicked. Event handler:
Step 2: Define the event handler (JavaScript function): showAll() for both events. In the event handler, create an object.
.
window.onload = function() { showAll();
}
onclick. Add following code inside .
var btn_all = document.getElementById(“button_all”); btn_all.addEventListener(‘click’, showAll);
XMLHttpRequest
var xmlhttp = new XMLHttpRequest();
//More code will be implemented in the following steps
Step 3: Define the response actions when the server’s response is received.
Step 4: Define the request that is sent through POST:
Step 5: Set the request header and send the request.
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status ==200){
var mesgs = document.getElementById(“entries”);
mesgs.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(“POST”, “queryEntries_WS3.php”,true);
xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”); xmlhttp.send(“show=all”);
Step 6: Hide the “Show All” button from the full list display view (as in Fig. 1), as follows:
document.getElementById(“button_all”).style.display = “none”;
Task 2.2: Implement client-side code for loading selected entries based
on “Major” or “Course” and adding new student into the attendance
system
When the “Filter by Major” button is clicked, the systems loads and displays all the attendance entries whose student major matches the entered text in the textbox above the “Filter by Major” button, using AJAX.
Step 1: In index_WS3.html, add an event handler on the button “Filter by Major”, so that when clicked, the JavaScript function filterM() will be called.
Step 2: Define the event handler (JavaScript function): filterM() for the event. In the event handler, create an XMLHttpRequest object and define the response actions when the server’s response is received, following steps 2 and 3 in Task 2.1.
document.getElementById(“majBtn”).addEventListener(‘click’, filterM);
function filterM() {
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var mesgs = document.getElementById(“entries”); mesgs.innerHTML = xmlhttp.responseText;
} }
//More code will be implemented in the following steps.
}
Define the request that is sent by POST as follows:
With reference to step 5 in Task 2.1, send the above POST request which contains the value entered by the user in the textbox above “Filter by Major” button using the format of “show=major&value=…”.
xmlhttp.open(“POST”, “queryEntries_WS3.php”, true);
xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
xmlhttp.send(“show=major&bymajor=”+document.getElementById(“major”).value);
Step 3: Display the “Show All” button in the page view (as in Fig. 2) through modifying the display properties of the “Show All” button, with reference to step 6 in Task 2.1. In addition, clear the filter value (e.g. “BBA” in Fig. 2) entered by the user in the textbox above “Filter by Major” button after receiving the AJAX response.
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var mesgs = document.getElementById(“entries”); mesgs.innerHTML = xmlhttp.responseText; document.getElementById(“major”).value = “”;
} }
btn_all.style.display = “block”;
Step 4: Similar to the above steps, implement the client-side code to achieve the functionality that when “Filter by Course” button is clicked, load and display all the attendance entries whose course code matches with the entered text in the textbox above the “Filter by Course” button, using AJAX by implementing codes in filterC().
Please note that the “Show All” button should also be displayed when a course attendance list filtered by course is displayed. In addition, clear the filter value (e.g. “COMP3322” in Fig. 3) entered by the user in the textbox above “Filter by Course” button after receiving the AJAX response.
Note: The format of passing data when “Filter by Course” button is clicked is “show=course&value=…”.
Step 5: Implement a JavaScript function addstudent() which will be called when “Add a student” button is clicked. Notice that this function will only be called when
• All the attributes are filled (include student name, student major, student course, student course date and student attendance)
• The entered student course date format matches with the date format of YYYY-MM- DD, which Y represents year, M represents month and D represents day.
• The entered student attendance is either “PRESENT” or “ABSENT” (case-sensitive).
document.getElementById(“cBtn”).addEventListener(‘click’, filterC);
xmlhttp.send(“show=course&bycourse=”+document.getElementById(“course”).value);
Otherwise an alert box displaying the message “Check your input date format (YYYY-MM-DD), Attendance record (PRESENT/ABSENT) and whether all fields are filled.” will be shown.
function addstudent(){
let sname = document.getElementById(“newname”); if (sname.validity.valueMissing) {
alert(“Missing student name!!”); sname.focus();
return; }
// other attributes are omitted here, you need to finish it by yourself. }
If user’s input satisfies the above conditions, you need to retrieve the values entered by the user in the input boxes and pass all the values through AJAX to queryEntries_WS3.php using “POST” method.
Remember to clear all the values (include student name, student major, student course, student course date and student attendance) entered by the user in the textboxes above “Add a student” button after receiving the AJAX response.
Note: The format of passing data when “Add a student” button is clicked is “show=add&value=…”.
Task 3: Implement server-side code for loading entries from the database and adding new student into the attendance system
In queryEntries_WS3.php, load the required entries from the database upon client’s request.
Step1: Connect to database at sophia.cs.hku.hk. Replace the ‘user-name’, ‘password’ and ‘database name’ with your CS username, MySQL password and your database (same as your CS username) which you create on the MySQL server at sophia.
//Connect to database
$conn=mysqli_connect(‘sophia.cs.hku.hk’, ‘user-name’, ‘password’, ‘database name’) or
die(‘Error! ‘. mysqli_connect_error($conn));
?>
, followed by printing the student name and student major (with heading level 3
), as well as the course code and date (with heading level 5
).
(h3 tag) (h5 tag)
Upon finishing this task, it is expected the system can achieve the following functions:
1. Display all the students’ records in the attendance system when the page is loaded (as Fig.
1 shows).
2. Display part of the students’ records that are either filtered by students’ major or course
//Construct your SQL query here
$query = ‘
select * from attendancelist’;
//Execute SQL query $result =
mysqli_query($conn, $query) or die(‘Error! ‘. mysql_error($conn));
while($row = mysqli_fetch_array($result)) {
print “
“;
print ““.$row[‘attendOrNot’].”“;
print ” …”//Add code to display the entries
print “
(h3 tag) (h5 tag)
Upon finishing this task, it is expected the system can achieve the following functions:
1. Display all the students’ records in the attendance system when the page is loaded (as Fig.
1 shows).
2. Display part of the students’ records that are either filtered by students’ major or course
//Construct your SQL query here
$query = ‘
select * from attendancelist’;
//Execute SQL query $result =
mysqli_query($conn, $query) or die(‘Error! ‘. mysql_error($conn));
while($row = mysqli_fetch_array($result)) {
print “
print ““.$row[‘attendOrNot’].”“;
print ” …”//Add code to display the entries
print “
“;
}
when the “Filter by Major” or “Filter by Course” button is clicked (as Fig. 2 and Fig. 3 show).
3. Display all the students’ record in the attendance system when the “Show All” button is
clicked (the “Show All” button is only displayed when filtered list is displayed).
4. Allows users to add a new student and all the students’ records (including the newly added one) would be displayed when the “Add a student” button is clicked (as Fig. 4 and Fig. 5
show).
Task 4: Toggle PRESENT/ABSENT for changing attendance record
Tapping the word PRESENT or ABSENT in each entry on the page will change the status from one to the other, and initiate AJAX communication to the server for changing the attribute “attendOrNot” of this entry in the database table, without reloading the entire web page.
Task 4.1
Implement the JavaScript function changeState(elem) as the event handler in index_WS3.html. With reference to the steps in Task 2.1, implement the AJAX code for asynchronous communication with the server (send the request through
“GET”).
Add the “onclick” event handler to the element of each display entry (do this by adding
the code to queryEntries_WS3.php).
function changeState(elem) {
var oldValue = elem.innerHTML;
var newvalue;
var itemID = elem.parentNode.getAttribute(‘id’); if (oldValue == ‘PRESENT’) {
newvalue = ‘ABSENT’; } else {
newvalue = ‘PRESENT’; }
var xmlhttp = new XMLHttpRequest();
// Add AJAX code here.
Hint: the request that sent through GET:
Task 4.2
Under updateState_WS3.php, implement the server-side logic in order to change the “attendOrNot” attribute of the corresponding entry in the database, as well as print out the updated attendance status. The following code is given for your reference.
xmlhttp.open(“GET”, “updateState_WS3.php?id=”+itemID+”&value=”+newvalue,true);
$conn=mysqli_connect(‘sophia.cs.hku.hk’, ‘user-name’, ‘password’, ‘database name’) or die (‘Error!
‘.mysqli_connect_error($conn));
// Implement the code here.
mysqli_close($conn);
Upon finishing this task, by clicking on the word PRESENT or ABSENT in each display entry on the page, you can change the attendance status of the student by updating the database as well as showing the new attendance status without re-loading the page.
Fig. 6 Before click “PRESENT” before Alice Fig. 7 After click “PRESENT” before Alice
Upload and Test
Use any FTP Client to connect to your CS account at the server i7.cs.hku.hk and create a new directory Workshop3 under your public_html. Then upload the index_WS3.html file to the Workshop3 directory.
Browse and test your webpage at: https://i7.cs.hku.hk/~[your_CSID]/Workshop3/index_WS3.html