Choose the most correct answer and write its letter in the answer booklet provided: (0.5 Marks Each)
i. What server support Ajax?
A. WWW
B. SMTP
C. HTTP
D. POP3
Answer (Click to show)
C. HTTP
Explanation:Â Ajax relies on the HTTP protocol to send and receive data asynchronously between the client and server.
ii. What is the correct syntax of the declaration which defines the XML version?
A. <xml version="A.0" />
B. <?xml version="A.0"?>
C. <?xml version="A.0" />
D. <xml version=yes>
Answer (Click to show)
B.
Explanation: XML declaration starts with <?xml and ends with ?>. The version attribute is required.
iii. Which formats are supported by Ajax to send and receive information?
A. JSON, XML, HTML, SQL, MySQL, and Text Files
B. JSON, XML, HTML, and Text Files
C. JSON, XML, HTML, NoSQL, and Oracle
D. JAVA, JSON, XML, HTML, Oracle, and Text Files
Answer (Click to show)
B. JSON, XML, HTML, and Text Files
Explanation:Â Ajax can handle plain text, HTML, XML, and JSON. It does not directly support SQL, MySQL, or Oracle formats.
iv. Which statement is true?
A. All XML elements must be in lower case
B. All XML elements must have a closing tag
C. All XML documents must have a DTD
D. All the statements are true
Answer (Click to show)
B. All XML elements must have a closing tag
Explanation:Â XML is case-sensitive and requires proper nesting and closing tags. DTD is optional.
v. Which of the following is used to display the output in PHP?
A. Echo
B. Both (a) and (d)
C. Write
D. Print
Answer (Click to show)
B. Both (a) and (d)
Explanation: Both echo and print are used to output data in PHP.
vi. Which of the following role of web service architecture provides a central place where developers can publish new services or find existing ones?
A. Service Provider
B. Service Registry
C. Service Requestor
D. Service Consumer
Answer (Click to show)
B. Service Registry
Explanation:Â UDDI or Service Registry acts as a directory for web services.
vii. If there is no error, then what will the error() method return?
A. True
B. Empty String
C. 0
D. False.
Answer (Click to show)
C. 0
Explanation: In many languages (like PHP’s error_get_last()), no error returns NULL or 0 depending on context. But in Ajax/JS error handling, it returns null.
viii. Which is the correct symbol to insert a comment in JSON?
A. //
B. /…/
C. JSON doesn’t support comments
D. <!-....-->
Answer (Click to show)
C. JSON doesn’t support comments
Explanation:Â JSON does not allow comments. Use external documentation instead.
ix. How do you represent a JSON array of strings?
A. {“days”:“SUN”,“MON”,“TUE”,“WED”,“THU”,“FRI”,“SAT”}}
B. {“days” = [“SUN”,“MON”,“TUE”,“WED”,“THU”,“FRI”,“SAT”]}
C. {“days”:[“SUN”,“MON”,“TUE”,“WED”,“THU”,“FRI”,“SAT”]}
D. {“days” = {“SUN”,“MON”,“TUE”,“WED”,“THU”,“FRI”,“SAT”}} “THU”,“FRI”,“SAT”}
Answer (Click to show)
C. {“days”:[“SUN”,“MON”,“TUE”,“WED”,“THU”,“FRI”,“SAT”]}
Explanation: JSON uses : after key, and arrays are in square brackets [].
x. Which of the following function displays the information about PHP and its configuration?
A. php_info()
B. info()
C. phpinfo()
D. phpinfo()
Answer (Click to show)
C. phpinfo()
Explanation:Â phpinfo()Â is a built-in PHP function that outputs PHP configuration info.
Question Two
Match the item in Column A with its corresponding item in Column B. (0.5 Marks Each)
Column A
Column B
i. onreadystatechange
A. request received
ii. Http Status = 400
B. XML
iii. readyState = 2
C. Server not Found
iv. REST
D. Provider of a web service on an online directory
v. Web Services Definition Language
E. XML document depends on other external files
vi. One among the principles of REST architecture
F. Internal server error
vii. XML stand alone = YES
G. Fixed width
viii. Styling language for xml
H. Processing request
ix. .container-fluid
I. Set with an JavaScript event handler that fires at each state change
x. Helper classes
J. Uniform Interface
K. XML/JSON/TEXT
L. XML based interface for describing the functionalities of the web service
M. XML document does not depending on other external files
N. XSLT
O. Full width
P. Make customization as quickly as possible
Answers (Click to show)
i. onreadystatechange → I. Set with an JavaScript event handler that fires at each state change
**ii. Http Status = 400 → C. Server not Found **
iii. readyState = 2 → A. Request Received
iv. REST → K. XML/JSON/TEXT
v. Web Services Definition Language → L. XML based interface for describing the functionalities of the web service
vi. One among the principles of REST architecture → J. Uniform Interface
vii. XML stand alone = YES → M. XML document does not depending on other external files
viii. Styling language for xml → N. XSLT
ix. .container-fluid → O. Full width
x. Helper classes → P. Make customization as quickly as possible
Question Three
Answer the following questions: - (1 Mark Each)
a) HTTP is a stateless protocol. Explain.
Answer (Click to show)
HTTP being a stateless protocol means that each request from a client to a server is treated as an independent transaction that is unrelated to any previous request. The server does not retain any information or memory about the client’s state between requests. This means that after sending a response to a client, the server forgets everything about that interaction, and each subsequent request must be treated as if it were the first time the client is communicating with the server.
b) Explain the two ways to make HTTP a state full protocol. (1 Mark)
Answer (Click to show)
The two ways to make HTTP stateful are:
Cookies: Small pieces of data stored on the client’s browser that are sent to the server with each request, allowing the server to identify returning users and maintain session information across multiple requests.
Summary:(Cookies - Store session data on the client side, sent with each request.)
Sessions: Server side storage mechanism that maintains user-specific data identified by a unique session ID (typically stored in a cookie or passed via URL), enabling the server to remember user interactions and state across multiple HTTP requests.
Summary:(Sessions - Store data on the server side, identified by a session ID.)
c) Explain the differences between Simple Object Access Protocol (SOAP) and Representational State Transfer (REST) web services. (2 Marks)
Answer (Click to show)
SOAP vs REST Differences:
Protocol vs Architecture: SOAP is a protocol with strict standards and specifications, while REST is an architectural style with more flexible constraints and guidelines.
Message Format: SOAP uses only XML for message formatting and requires envelope structures, while REST supports multiple formats including JSON, XML, HTML, and plain text.
Transport Protocol: SOAP can work with multiple transport protocols (HTTP, SMTP, TCP, etc.), while REST primarily works with HTTP/HTTPS.
State: SOAP can be stateful or stateless, while REST is designed to be stateless by nature.
Performance: REST is generally faster and uses fewer bandwidth resources compared to SOAP, which has more overhead due to extensive XML markup and envelope requirements.
Security: SOAP has built-in security (WS-Security) and transaction compliance, while REST relies on underlying transport security (HTTPS) for security.
Caching: REST supports caching of responses, improving performance, while SOAP does not support caching by default.
d) PHP is “a weakly typed language”. Explain what this statement means as regards to php variables. (1 Mark)
Answer (Click to show)
PHP being a “weakly typed language” means that variables do not require explicit declaration of data types, and the language automatically converts (type juggling) variables from one data type to another as needed based on the context of usage. For example, a variable can be assigned a string value and later reassigned an integer value without any type declaration or casting errors. PHP automatically determines and converts the variable type during runtime depending on the operation being performed.
SECTION B: (45 MARKS)
Attempt THREE (3) out of FOUR (4) questions in this section.
Question Four
You have been hired as a front end developer at one of the ECommerce company. The first day of your work at the company you realize that company’s website is not okay. You decided to use bootstrap framework to revamp the website to make it more attractive and user friendly. Among the features of the bootstrap you have decided to use are carousel and pagination. You have decided to divide the contents of the website into five pages ie. page1.html, page2.html, page3.html, page4.html and page5.html. Among the images that describe the company are image1.jpg, image2.jpg, image3.jpg, image4.jpg and image5.jpg. You thought it will be better if the images will be in a slide show.
In your design show how you will use bootstrap carousel and pagination to create a slide show of the mentioned images and pagination of the mentioned pages respectively.
Hint: use carousel-indicator class to show the captions of each slide, carousel-inner class to add slides to the carousel, carousel-control-prev and carousel-control-next class to allow the user to go back and forward between the slides. (15 Marks)
Used carousel-indicator class to create navigation indicators at the bottom of each slide, which also show captions when hovered over
Used carousel-inner class to wrap all slides containing the five company images (image1.jpg to image5.jpg)
Used carousel-control-prev and carousel-control-next classes to add navigation buttons that allow users to move back and forth between slides
Added captions to each slide using carousel-caption class to provide descriptions for each image
Pagination Implementation:
Created pagination using Bootstrap’s pagination class to navigate between five pages (page1.html to page5.html)
Used page-item and page-link classes to style individual page links
Added previous («) and next (») buttons for easier navigation
Highlighted the active page using active class
User Experience Features:
The carousel automatically rotates through images with smooth transitions
Users can manually navigate slides using indicators or prev/next buttons
Pagination provides clear navigation structure for the website content
The design is fully responsive and mobile-friendly due to Bootstrap framework
Question Five
Answer the following questions: -
a. Create an Ajax-based product catalog that obtains its data from JSON files located on the server. The data should be separated into four JSON files. The first file should be a summary file, containing a list of products. Each product should have a title, an image filename for a thumbnail image and a price. The second file should contain a list of descriptions for each product. The third file should contain a list of filenames for the full-size product images. The last file should contain a list of the thumbnail image file names. Each item in a catalogue should have a unique ID that should be included with the entries for that product in every file. Next, create an Ajax-enabled web page that displays the product information in a table. The catalog should initially display a list of product names with their associated thumbnail images and prices. When the mouse hovers over a thumbnail image, the larger product image should be displayed. When the user moves the mouse away from that image, the original thumbnail should be redisplayed. You should provide a button that the user can click to display the product description. (7 Marks)
[ { "id": 1, "description": "High-performance laptop with 16GB RAM, 512GB SSD, and Intel Core i7 processor. Perfect for professional use and gaming." }, { "id": 2, "description": "Ergonomic wireless mouse with adjustable DPI, long battery life, and smooth tracking on multiple surfaces." }, { "id": 3, "description": "RGB mechanical keyboard with blue switches, aluminum frame, and programmable macros for enhanced productivity." }, { "id": 4, "description": "Full HD 24-inch monitor with IPS panel, 75Hz refresh rate, and built-in speakers for immersive viewing experience." }]
b. Write a PHP script that obtains a URL and its description from a user through html form and stores the information into a database using MySQL. Use URL and URLtable as the name of the database and table respectively. The first field of the table should contain an actual URL, and the second, which is named Description, should contain a description of the URL. Use www.udom.ac.tz as the first URL, and input UDOM as its description. The second URL should be www.ratiba.udom.ac.tz, and the description should be UDOM Time Table System. The third URL should be www.civeclassroom.udom.ac.tz, and its description should be CIVE digital classroom. The fourth URL should be www.civeipt.udom.ac.tz, and its description should be CIVE Industrial Practical Training. After each new URL is submitted, print the contents of the database in a table format. (8 Marks)
Answer (Click to show)
PHP Script: url_manager.php
<?php/* =============================== DATABASE CONFIGURATION =============================== */$servername = "localhost";$username = "root";$password = "";$dbname = "URL";/* =============================== CREATE DATABASE CONNECTION =============================== */$conn = new mysqli($servername, $username, $password);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}/* =============================== CREATE DATABASE IF NOT EXISTS =============================== */$sql = "CREATE DATABASE IF NOT EXISTS $dbname";$conn->query($sql);$conn->select_db($dbname);/* =============================== CREATE TABLE IF NOT EXISTS =============================== */$table_sql = "CREATE TABLE IF NOT EXISTS URLtable ( id INT AUTO_INCREMENT PRIMARY KEY, url VARCHAR(255) NOT NULL, description VARCHAR(255) NOT NULL)";$conn->query($table_sql);/* =============================== INSERT DEFAULT URL RECORDS =============================== */$default_data = [ ['www.udom.ac.tz', 'UDOM'], ['www.ratiba.udom.ac.tz', 'UDOM Time Table System'], ['www.civeclassroom.udom.ac.tz', 'CIVE digital classroom'], ['www.civeipt.udom.ac.tz', 'CIVE Industrial Practical Training']];foreach ($default_data as $data) { $check = "SELECT * FROM URLtable WHERE url = '{$data[0]}'"; $result = $conn->query($check); // Insert only if URL does not already exist if ($result->num_rows == 0) { $insert = "INSERT INTO URLtable (url, description) VALUES ('{$data[0]}', '{$data[1]}')"; $conn->query($insert); }}/* =============================== HANDLE FORM SUBMISSION =============================== */if ($_SERVER["REQUEST_METHOD"] == "POST") { // Trim inputs to remove spaces before and after $url = trim($_POST['url']); $description = trim($_POST['description']); // Server-side validation if (!empty($url) && !empty($description)) { $sql = "INSERT INTO URLtable (url, description) VALUES ('$url', '$description')"; $conn->query($sql); }}?><!DOCTYPE html><html><head> <title>URL Manager</title></head><body><h2>Add New URL</h2><!-- HTML form for user input --><form method="POST"> <label>URL:</label><br> <input type="text" name="url" required><br><br> <label>Description:</label><br> <input type="text" name="description" required><br><br> <input type="submit" value="Submit"></form><h2>Stored URLs</h2><?php/* =============================== DISPLAY DATABASE CONTENTS =============================== */$result = $conn->query("SELECT * FROM URLtable");echo "<table border='1' cellpadding='5'> <tr> <th>ID</th> <th>URL</th> <th>Description</th> </tr>";while ($row = $result->fetch_assoc()) { echo "<tr> <td>{$row['id']}</td> <td>{$row['url']}</td> <td>{$row['description']}</td> </tr>";}echo "</table>";// Close database connection$conn->close();?></body></html>
Question Six
Answer the following questions: -
a. XML plays an important role in the current world of web development. It is completely beneficial for those who want to use web technology to distribute information across the web.
i. Create a web service in xml format which contain information of the students such as: Students first name, last name, RegNo, Age, Gender, Courses, and Program. (3 Marks)
ii. Using PHP write a script that will read the XML web service in part (i) and display the results in a web browser in JSON format. (3 Marks)
Answer (Click to show)
PHP Script: read_xml_to_json.php
<?php// read_xml_to_json.phpheader('Content-Type: application/json');// Load XML file$xmlFile = 'students.xml';//Check if the xml file existsif (!file_exists($xmlFile)) { echo json_encode(["error" => "XML file not found"], JSON_PRETTY_PRINT); exit;}//Read the contents of the xml file$xml = simplexml_load_file($xmlFile);if ($xml === false) { echo json_encode(["error" => "Failed to load XML"], JSON_PRETTY_PRINT); exit;}// Convert to JSON with pretty print$json = json_encode($xml, JSON_PRETTY_PRINT);// Output the JSON to the browserecho json_encode($json);?>
b. Suppose that there is a web service named adventure.php, located on your web server in the same directory as your code. This service outputs XML data describing a situation and options a player can pick (you can choose your own adventure style game). In this problem you will use Ajax to contact the web service (using a GET request), examine its XML data, and display the questions and options in the game. The XML data returned by the web service consists of an overall document element called adventure that contains a situation tag, an answers tag and an end tag. The answers tag contains a series of one or more answer elements inside it. The format of the XML matches the following.
<adventure> <situation>The dragon is looking at you</situation> <answers> <answer>run screaming</answer> <answer>draw your sword</answer> <answer>be very polite</answer> <answer>sneeze</answer> </answers> <end reason="ooh! The dragon accidentally stepped on you" /></adventure>
Assume the code you are writing will go into adventure.js, linked from the following script.
<body> <h1>Choose your own adventure</h1> <div id="container"> <fieldset id="situation"> <p id="situationparagraph"></p> </fieldset> <fieldset id="answer"></fieldset> </div></body>
When the page loads send an AJAX request to the adventure.php service and pass it a parameter named situation with the value begin. Insert the questions you get back into the situationparagraph. Add a button to the answer fieldset for each answer tag you receive. Set these buttons so that if they are clicked your page will send an Ajax request to adventure.php with the situation parameter set to the text on the button. This request will return the same sort of data which should be dealt with in the same way. The buttons displayed should only ever be the current options, no old options should show. If instead of receiving XML back that contains a question tag you receive XML with an end tag, place the text of the reason attribute of the end tag in the situationparagraph and make sure no buttons are showing. (9 Marks)
All codes are in the answers below:
Answer (Click to show)
PHP Script: adventure.php
<?phpheader('Content-Type: text/xml');$situation = $_GET['situation'] ?? 'begin';echo '<?xml version="1.0" encoding="UTF-8"?>';echo '<adventure>';switch($situation) { case 'begin': echo '<situation>You are at the entrance of a dark cave. What do you do?</situation>'; echo '<answers><answer>Enter the cave</answer><answer>Wait outside</answer><answer>Run away</answer><answer>Call for help</answer></answers>'; break; case 'Enter the cave': echo '<situation>You see a dragon sleeping on gold!</situation>'; echo '<answers><answer>Try to sneak past</answer><answer>Wake the dragon</answer><answer>Take gold quietly</answer><answer>Run back out</answer></answers>'; break; case 'Wake the dragon': echo '<situation>The dragon is looking at you</situation>'; echo '<answers><answer>run screaming</answer><answer>draw your sword</answer><answer>be very polite</answer><answer>sneeze</answer></answers>'; break; case 'run screaming': case 'sneeze': echo '<end reason="Ooh! The dragon accidentally stepped on you" />'; break; case 'draw your sword': echo '<end reason="The dragon breathes fire and you are defeated!" />'; break; case 'be very polite': echo '<situation>The dragon is impressed by your manners and offers you a ride!</situation>'; echo '<answers><answer>Accept the ride</answer><answer>Politely decline</answer></answers>'; break; case 'Accept the ride': echo '<end reason="You fly on the dragon and become legends! YOU WIN!" />'; break; default: echo '<situation>The adventure continues...</situation>'; echo '<answers><answer>Continue</answer><answer>Restart</answer></answers>';}echo '</adventure>';?>
Answer (Click to show)
JavaScript File: adventure.js
// adventure.js - AJAX Choose Your Own Adventureconst serviceUrl = 'adventure.php'; // Web service URL// Send AJAX GET request with a situation parameterfunction getAdventureData(situationParam) { const xhr = new XMLHttpRequest(); xhr.open('GET', serviceUrl + '?situation=' + encodeURIComponent(situationParam), true); // On successful response xhr.onload = function() { if (xhr.status === 200) { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xhr.responseText, 'text/xml'); processAdventureData(xmlDoc); // Process XML response } else { document.getElementById('situationparagraph').textContent = 'Error loading game data.'; } }; // Handle network errors xhr.onerror = function() { document.getElementById('situationparagraph').textContent = 'Network error. Check your connection.'; }; xhr.send();}// Process XML and update the pagefunction processAdventureData(xmlData) { const situationPara = document.getElementById('situationparagraph'); const answerFieldset = document.getElementById('answer'); // Check for <end> element (game over) const endElement = xmlData.getElementsByTagName('end')[0]; if (endElement) { situationPara.textContent = endElement.getAttribute('reason'); answerFieldset.innerHTML = ''; // Remove all buttons return; } // Update situation text const situation = xmlData.getElementsByTagName('situation')[0]; if (situation) situationPara.textContent = situation.textContent; // Clear old buttons answerFieldset.innerHTML = ''; // Create buttons for each <answer> const answers = xmlData.getElementsByTagName('answer'); for (let i = 0; i < answers.length; i++) { const text = answers[i].textContent; const btn = document.createElement('button'); btn.textContent = text; // Button styling btn.style.margin = '5px'; btn.style.padding = '8px 15px'; btn.style.backgroundColor = '#4CAF50'; btn.style.color = 'white'; btn.style.border = 'none'; btn.style.borderRadius = '5px'; btn.style.cursor = 'pointer'; btn.onmouseover = () => btn.style.backgroundColor = '#45a049'; btn.onmouseout = () => btn.style.backgroundColor = '#4CAF50'; // Click event sends new AJAX request btn.onclick = () => getAdventureData(text); answerFieldset.appendChild(btn); }}// Initialize game on page loadwindow.onload = function() { getAdventureData('begin'); // Start with situation=begin};
Answer (Click to show)
HTML File: adventure.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Choose Your Own Adventure</title> <style> body { font-family: Arial; margin: 20px; } fieldset { border:2px solid #4CAF50; border-radius:6px; padding:10px; margin-bottom:15px; } #situationparagraph { min-height:50px; font-size:16px; color:#333; } button { cursor:pointer; } </style></head><body> <h1>Choose Your Own Adventure</h1> <div id="container"> <fieldset id="situation"> <legend>Situation</legend> <p id="situationparagraph">Loading adventure...</p> </fieldset> <fieldset id="answer"> <legend>Choose Your Action</legend> </fieldset> </div> <script src="adventure.js"></script></body></html>
Question Seven
The University of Dodoma through its College of Informatics and Virtual Education (CIVE) has decided to create a web system to manage the whole process of Industrial Practical Training (IPT). The system was developed using PHP and MySQL database. The system has two parts, which are source codes and database. The database part is hosted at the server with IP Address 192.168.10.10 and the source code is hosted at the server with IP Address 192.168.10.20.
After the system has been deployed it was observed that the performance was poor as the system loads very slowly especially when the information are retrieved from the server. It was observed that the problem was due to huge amount of data that are loaded from the server. As an expert in web development, you have been consulted to give your advice. In your advice you suggested AJAX technology to be used to load data from the server to the client side so as to improve performance. Assume you want to load the following information from the table student (FName, SName, Program, Gender and RegNo). Write a script hosted at the source code server to show how you connect to the database, load data from the server using AJAX and display to the client in a table format. Use JQuery methods to send the AJAX requests.
Use the following credentials to access the database server: Udom_IPT as a database name, Password: 123_abc, username: udom_cive. (15 Marks)
Answer (Click to show)
PHP Script: get_students.php
<?php// get_students.php - Fetch student data via PDO and return JSONheader('Content-Type: application/json'); // Set JSON response// Database connection parameters$host = '192.168.10.10'; // DB server IP$db = 'Udom_IPT'; // Database name$user = 'udom_cive'; // Username$pass = '123_abc'; // Password$charset = 'utf8mb4'; // Charset// DSN for PDO$dsn = "mysql:host=$host;dbname=$db;charset=$charset";try { $pdo = new PDO($dsn, $user, $pass, $options); // Connect to DB} catch (PDOException $e) { echo json_encode(['success' => false, 'error' => 'DB connection failed: '.$e->getMessage()]); exit;}try { // Prepare and execute query $stmt = $pdo->query("SELECT FName, SName, Program, Gender, RegNo FROM student ORDER BY RegNo"); $students = $stmt->fetchAll(); // Fetch all results // Return JSON echo json_encode([ 'success' => true, 'count' => count($students), 'data' => $students ]);} catch (PDOException $e) { echo json_encode(['success' => false, 'error' => 'Query failed: '.$e->getMessage()]);}?>