Assignments On Class 24
PHP and JavaScript Integration
Here are a few assignments with solutions and detailed explanations related to integrating PHP and JavaScript. Each assignment focuses on different aspects of the PHP and JavaScript interaction concepts covered in the lecture.
Assignment 1: Passing Data from PHP to JavaScript
Objective: Create a PHP script that generates a list of items and passes it to JavaScript.
Instructions:
1. Create a PHP script named items.php.
2. In this script, create an array of at least five items (e.g., fruits, vegetables).
3. Pass this array to a JavaScript variable using json_encode().
4. Display the items in the browser console.
Solution:
items.php:
<?php
// Step 1: Create an array of items
$items = array("Apple", "Banana", "Carrot", "Date", "Eggplant");
// Step 2: Pass the array to JavaScript
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP to JavaScript Integration</title>
<script>
// Step 3: Convert PHP array to JavaScript array
var items = <?php echo json_encode($items); ?>;
console.log(items); // Output the items to the console
</script>
</head>
<body>
<h1>Check the console for the list of items!</h1>
</body>
</html>
Explanation:
- We created a PHP array called $items.
- We used json_encode() to convert this array into a format that JavaScript can understand.
- The resulting JavaScript array is logged to the console when the page is loaded.
Assignment 2: Sending Data from JavaScript to PHP using AJAX
Objective: Create a web page that allows users to submit their name and receive a greeting from PHP.
Instructions:
1. Create an HTML page named greet.html.
2. Include a form with an input field for the user's name and a button to submit.
3. Use AJAX to send the name to a PHP script called greet.php.
4. Display the response (greeting) on the web page.
Solution:
greet.html:
<!DOCTYPE html>
<html>
<head>
<title>AJAX Greeting</title>
<script>
function submitForm() {
var name = document.getElementById("name").value; // Get the name input
var xhr = new XMLHttpRequest();
xhr.open("POST", "greet.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("response").innerHTML = xhr.responseText; // Display the greeting
}
};
xhr.send("name=" + encodeURIComponent(name)); // Send the name to PHP
}
</script>
</head>
<body>
<h1>Enter Your Name</h1>
<input type="text" id="name" placeholder="Your Name">
<button type="button" onclick="submitForm()">Submit</button>
<div id="response"></div>
</body>
</html>
greet.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']); // Get the name sent from JavaScript
echo "Hello, " . $name . "! Welcome to our website."; // Send a greeting back
}
?>
Explanation:
- In greet.html, the user enters their name, which is sent to greet.php via AJAX when they click the submit button.
- The PHP script retrieves the name from the POST request and returns a greeting message.
- This greeting is displayed on the web page without a page refresh, thanks to AJAX.
Assignment 3: Using Fetch API to Send Data to PHP
Objective: Modify the previous assignment to use the Fetch API instead of XMLHttpRequest.
Instructions:
1. Create a new HTML page named fetch_greet.html.
2. Implement a form to accept a user’s name.
3. Use the Fetch API to send the name to the greet.php script.
4. Display the response (greeting) on the web page.
Solution:
fetch_greet.html:
<!DOCTYPE html>
<html>
<head>
<title>Fetch API Greeting</title>
<script>
function submitForm() {
var name = document.getElementById("name").value; // Get the name input
fetch("greet.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: "name=" + encodeURIComponent(name)
})
.then(response => response.text()) // Convert response to text
.then(data => {
document.getElementById("response").innerHTML = data; // Display the greeting
})
.catch(error => console.error('Error:', error)); // Handle any errors
}
</script>
</head>
<body>
<h1>Enter Your Name</h1>
<input type="text" id="name" placeholder="Your Name">
<button type="button" onclick="submitForm()">Submit</button>
<div id="response"></div>
</body>
</html>
greet.php: (remains unchanged from the previous example)
Explanation:
- In fetch_greet.html, we use the Fetch API to send the user’s name to greet.php.
- The response is then processed and displayed on the web page.
- This implementation is simpler and more modern compared to using XMLHttpRequest.
Conclusion
These assignments help students practice passing data between PHP and JavaScript using various methods, including JSON encoding and AJAX (both XMLHttpRequest and Fetch API). Understanding these interactions is vital for building dynamic web applications. Encourage students to experiment with variations of these assignments to reinforce their learning.
Assignment 4: Displaying User Input with Error Handling
Objective: Create a web page that allows users to submit their email address and provides feedback based on the validity of the email format.
Instructions:
1. Create an HTML page named email_validation.html.
2. Include an input field for the user to enter their email address and a submit button.
3. Use JavaScript to validate the email format before sending it to a PHP script named validate_email.php.
4. If the email format is invalid, display an error message. If valid, send the email to PHP and display a confirmation message.
Solution:
email_validation.html:
<!DOCTYPE html>
<html>
<head>
<title>Email Validation</title>
<script>
function validateEmail(email) {
// Basic email pattern
var pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email); // Returns true if email matches the pattern
}
function submitForm() {
var email = document.getElementById("email").value; // Get the email input
var responseDiv = document.getElementById("response");
if (!validateEmail(email)) {
responseDiv.innerHTML = "Please enter a valid email address."; // Show error message
responseDiv.style.color = "red";
return; // Stop further processing
}
fetch("validate_email.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: "email=" + encodeURIComponent(email)
})
.then(response => response.text())
.then(data => {
responseDiv.innerHTML = data; // Display the confirmation message
responseDiv.style.color = "green"; // Change text color to green
})
.catch(error => console.error('Error:', error)); // Handle errors
}
</script>
</head>
<body>
<h1>Enter Your Email Address</h1>
<input type="text" id="email" placeholder="Your Email">
<button type="button" onclick="submitForm()">Submit</button>
<div id="response"></div>
</body>
</html>
validate_email.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = htmlspecialchars($_POST['email']); // Retrieve the email sent from JavaScript
echo "Thank you! Your email address (" . $email . ") has been recorded."; // Confirmation message
}
?>
Explanation:
- The JavaScript function validateEmail checks if the entered email matches a basic regex pattern.
- If the email is invalid, an error message is displayed, and the form submission is halted.
- If valid, the email is sent to the validate_email.php script, which processes the input and returns a confirmation message.
Assignment 5: Dynamic Dropdown Using PHP and JavaScript
Objective: Create a dynamic dropdown list that populates based on a selection from another dropdown.
Instructions:
1. Create a PHP script named data.php that returns a list of fruits based on the selected category (e.g., tropical or berries).
2. Create an HTML page named dynamic_dropdown.html with two dropdowns:
o The first dropdown for selecting a category (e.g., Tropical, Berries).
o The second dropdown that will be populated based on the selection from the first.
3. Use JavaScript to make an AJAX call to data.php to fetch the corresponding fruits.
Solution:
data.php:
<?php
if (isset($_POST['category'])) {
$category = $_POST['category'];
$data = array();
if ($category == "Tropical") {
$data = array("Mango", "Pineapple", "Banana");
} elseif ($category == "Berries") {
$data = array("Strawberry", "Blueberry", "Raspberry");
}
echo json_encode($data); // Return the data as a JSON array
}
?>
dynamic_dropdown.html:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Dropdown Example</title>
<script>
function fetchFruits() {
var category = document.getElementById("category").value; // Get selected category
var fruitDropdown = document.getElementById("fruits");
fruitDropdown.innerHTML = ""; // Clear previous options
fetch("data.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: "category=" + encodeURIComponent(category)
})
.then(response => response.json())
.then(data => {
data.forEach(fruit => {
var option = document.createElement("option");
option.value = fruit;
option.textContent = fruit;
fruitDropdown.appendChild(option); // Add fruit options to the dropdown
});
})
.catch(error => console.error('Error:', error)); // Handle errors
}
</script>
</head>
<body>
<h1>Select a Fruit Category</h1>
<select id="category" onchange="fetchFruits()">
<option value="">-- Select Category --</option>
<option value="Tropical">Tropical</option>
<option value="Berries">Berries</option>
</select>
<h2>Select a Fruit</h2>
<select id="fruits">
<option value="">-- Select Fruit --</option>
</select>
</body>
</html>
Explanation:
- The first dropdown allows the user to select a category.
- Upon selection, the fetchFruits() function is triggered, which sends the selected category to data.php.
- The server responds with a JSON array of fruits, which is then used to populate the second dropdown dynamically.
Assignment 6: Using Session Data with PHP and JavaScript
Objective: Create a web page that allows users to log in and display a personalized greeting using session data.
Instructions:
1. Create a PHP script named login.php that processes user login and sets a session variable for the username.
2. Create an HTML page named session_greeting.html that checks for the session and displays a personalized greeting.
3. Use JavaScript to fetch the username from the session.
Solution:
login.php:
<?php
session_start(); // Start the session
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = htmlspecialchars($_POST['username']); // Get the username from the POST request
$_SESSION['username'] = $username; // Set session variable
echo "Login successful!"; // Response message
}
?>
session_greeting.html:
<!DOCTYPE html>
<html>
<head>
<title>Session Greeting</title>
<script>
function fetchGreeting() {
fetch("get_session.php")
.then(response => response.text())
.then(data => {
document.getElementById("greeting").innerHTML = data; // Display the greeting
})
.catch(error => console.error('Error:', error)); // Handle errors
}
</script>
</head>
<body onload="fetchGreeting()">
<h1>Welcome!</h1>
<div id="greeting"></div>
</body>
</html>
get_session.php:
<?php
session_start(); // Start the session
if (isset($_SESSION['username'])) {
echo "Hello, " . htmlspecialchars($_SESSION['username']) . "!"; // Personal greeting
} else {
echo "Hello, Guest! Please log in.";
}
?>
Explanation:
- login.php processes a login form by setting a session variable with the username.
- session_greeting.html calls the get_session.php script on page load to check the session and retrieve the username.
- If the user is logged in, a personalized greeting is displayed; otherwise, a guest message appears.
Conclusion
These additional assignments enhance the understanding of PHP and JavaScript integration by introducing concepts such as email validation, dynamic dropdowns, and session management. Encourage students to modify and extend these examples to deepen their comprehension and develop practical skills in web development.