_Unit_4_and_Unit_5
_Unit_4_and_Unit_5
1.Event Handler
Event Handlers in JavaScript
Event handlers in JavaScript are methods that allow you to run JavaScript code
or functions when specific events occur on an HTML element. These events
make web pages interactive and dynamic.
Here’s a detailed explanation of the event handlers onclick , onload , onchange ,
and onmouseover (commonly referred to as onmousehover ).
Syntax:
Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="alert('Button clicked!')">Click Me</bu
tton>
</body>
</html>
Output:
Useful for preloading data or images, and initializing functions after the web
page is fully loaded.
Syntax:
Example:
<!DOCTYPE html>
<html>
<body onload="console.log('Page is loaded')">
<h1>Welcome to the Website</h1>
</body>
</html>
Output:
When the page loads, "Page is loaded" is logged to the browser console.
Importance:
Syntax:
Example:
<!DOCTYPE html>
<html>
<body>
<label for="name">Enter your name:</label>
<input type="text" id="name" onchange="alert('You chang
ed the input!')">
</body>
</html>
Output:
When the user types something in the input box and moves away (loses focus),
an alert box appears with the message "You changed the input!".
Importance:
Syntax:
Example:
<!DOCTYPE html>
<html>
Output:
When the user hovers the mouse over the paragraph, its text color changes to
red.
Example:
2. Using Literals
Syntax:
Example:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial
<title>Word count</title>
</head>
<body>
<h1>Word count</h1>
<p>Enter the text in the box to count the words and click
<script>
function countWord() {
</body>
</html>
javascript
Copy code
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Optional: Code that runs regardless of success or fa
ilure
1. try block:
Contains the code that might throw an error. If an error occurs, control is
passed to the catch block.
2. catch block:
Handles the error. It takes an error object as a parameter, which contains
information about the error.
javascript
Copy code
// Exception handling example to handle TypeError
try {
let student = undefined; // An undefined object
console.log(student.name); // Attempt to access 'name'
property (causes TypeError)
Explanation of Code:
1. try Block:
2. catch Block:
3. finally Block:
4. Output:
javascript
Copy code
TypeError occurred: Cannot access property of undefined.
Execution completed.
javascript
Copy code
try {
let student = null;
if (student === null) {
throw new TypeError("Student object cannot be nul
l.");
}
} catch (error) {
console.error(error.message);
} finally {
console.log("Program execution completed.");
}
Key Takeaways:
1. Use try...catch to catch runtime errors.
4. You can manually throw errors for better control and debugging.
Check if input follows the correct format (e.g., emails, phone numbers).
2. Server-Side Validation:
Performed on the server to ensure data integrity and security. This is
crucial because client-side validation can be bypassed.
2. Length Validation
Checks whether the input meets a specific character length.
3. Format Validation
Ensures input matches a specific format, such as emails, phone numbers,
or dates.
4. Range Validation
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
Explanation:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Email Validation</title>
<script>
Explanation:
Alerts the user if the email doesn't match the expected pattern.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Range Validation</title>
<script>
Explanation:
Validates whether the input is a number and checks if it lies between 18 and
60.
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Multiple Validation Example</title>
<script>
function validateForm() {
return true;
}
</script>
</head>
<body>
<h2>Form with Multiple Validations</h2>
<form onsubmit="return validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><b
r><br>
<label for="password">Password:</label>
<input type="password" id="password" name="passwor
d"><br><br>
Use semantic HTML attributes like required , pattern , and min / max for basic
client-side validation.
Unit 5
Introduction to PHP
PHP (Hypertext Preprocessor) is an open-source, server-side scripting
language primarily used for web development. It is embedded in HTML and
executed on the server, making it highly efficient for dynamic web page
creation. PHP is widely used for creating dynamic websites, interactive web
applications, and backend services. It can interact with databases, handle
forms, and manage sessions effectively.
2. Server-Side Execution:
PHP scripts are executed on the server, and the result (HTML) is sent to the
client’s browser.
3. Cross-Platform Compatibility:
PHP runs on all major operating systems (Windows, Linux, macOS) and
works with most web servers (Apache, Nginx, IIS).
5. Supports Databases:
8. Extensibility:
PHP supports numerous libraries, frameworks (like Laravel, CodeIgniter),
and extensions to enhance functionality.
9. Security Features:
Provides built-in tools to handle security threats such as SQL injection, XSS,
and CSRF.
Applications of PHP
1. Web Development:
PHP is primarily used to build dynamic websites and web applications.
Examples include blogs, forums, and e-commerce platforms.
WordPress
Joomla
Drupal
3. E-commerce Platforms:
PHP is used to develop e-commerce sites with platforms like Magento,
WooCommerce, and custom shopping carts.
4. Database Integration:
PHP can create data-driven applications by integrating with databases like
MySQL and SQLite.
7. API Development:
PHP is used to build RESTful APIs that allow applications to communicate
with each other.
8. Web-Based Applications:
9. Email Management:
1. include():
The include() function takes all the text in a specified file and copies it into the
file that uses the include function. If there is any problem in loading a file, then
the include() function generates a warning but the script will continue
execution.
Example:
Create a file menu.php with the following content:
<a href="http://www.tutorialspoint.com/index.htm">Home</a>
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a>
<a href="http://www.tutorialspoint.com/ajax">AJAX</a>
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br /
>
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!
</p>
</body>
</html>
Output:
The content of menu.php will be included in the test.php file.
2. require():
The require() function takes all the text in a specified file and copies it into the
file that uses the include function. If there is any problem in loading a file, then
the require() function generates a fatal error and halts the execution of the
script.
So, there is no difference between require() and include() except how they
handle error conditions. It is recommended to use the require() function
instead of include() , because scripts should not continue executing if files are
missing or misnamed.
Example:
You can try using the above example with the require() function, and it will
generate the same result. But if you try the following two examples where the
file does not exist, you will get different results.
1. Using include :
html
Copy code
<html>
<body>
<?php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP
Output:
1. Using require :
html
Copy code
<html>
<body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP
file!</p>
</body>
</html>
Output:
This time, file execution halts, and nothing is displayed.
3. include_once() :
Ensures that the specified file is included only once during the execution of
the script, even if included multiple times.
Example:
File: x.php
<?php
echo "GEEKSFORGEEKS";
?>
<?php
include_once('header.inc.php');
include_once('header.inc.php');
?>
Output:
GEEKSFORGEEKS
4. require_once():
Similar to require , but ensures the file is included only once.
Using require_once :
<?php
require_once('header.inc.php');
require_once('header.inc.php');
?>
Output:
GEEKSFORGEEKS
2. if…else statement
3. if…elseif…else statement
4. switch statement
1. if Statement:
The if statement is used to execute a block of code only if the specified
condition evaluates to true. This is the simplest PHP conditional statement and
Syntax:
php
Copy code
if (condition)
{
// if TRUE then execute this code
}
Example:
php
Copy code
<?php
$x = 12;
if ($x > 0)
{
echo "The number is positive";
}
?>
Output:
The number is positive
2. if…else Statement:
You can enhance the decision-making process by providing an alternative
choice through adding an else statement to the if statement. The if...else
statement allows you to execute one block of code if the specified condition
evaluates to true and another block of code if it evaluates to false.
Syntax:
Example:
php
Copy code
<?php
$x = -12;
if ($x > 0)
echo "The number is positive";
else
echo "The number is negative";
?>
Output:
The number is negative
3. if…elseif…else Statement:
The is a special statement that is used to combine multiple
if...elseif...else
if...else statements. We use this when there are multiple conditions of TRUE
cases.
Syntax:
Example:
php
Copy code
<?php
$x = "August";
if ($x == "January")
{
echo "Happy Republic Day";
}
elseif ($x == "August")
{
echo "Happy Independence Day!!!";
}
else
{
Output:
Happy Independence Day!!!
4. switch Statement:
The switch statement performs in various cases i.e., it has various cases to
which it matches the condition and appropriately executes a particular case
block. It first evaluates an expression and then compares it with the values of
each case. If a case matches, then the same case is executed. To use switch ,
we need to get familiar with two different keywords:
break: Used to stop the automatic control flow into the next cases and exit
from the switch case.
default: Contains the code that would execute if none of the cases match.
Syntax:
php
Copy code
switch(expression)
{
case value1:
// code to be executed if n == value1
break;
case value2:
// code to be executed if n == value2
break;
case value3:
// code to be executed if n == value3
break;
......
default:
// code to be executed if n != any case
Example:
php
Copy code
<?php
$n = "February";
switch($n)
{
case "January":
echo "Its January";
break;
case "February":
echo "Its February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
default:
echo "Doesn't exist";
}
?>
Output:
Its February
1. for loop
2. while loop
3. do-while loop
4. foreach loop
1. for loop
This type of loop is used when the user knows in advance how many times the
block needs to execute.
These types of loops are also known as entry-controlled loops.
Parameters:
1. Initialization
2. Test Condition
3. Update Expression
Syntax:
php
Copy code
for (initialization expression; test condition; update expr
ession)
{
// code to be executed
}
3. If the condition is true , execute the loop body, then update the loop
variable.
Example:
php
Copy code
<?php
for ($num = 1; $num <= 10; $num += 2)
{
echo "$num \n";
}
?>
Output:
Copy code
1
3
5
7
9
Flow diagram
Syntax:
php
Copy code
while (condition)
{
// code to be executed
}
Example:
Output:
Copy code
4
6
8
10
12
php
Copy code
do
{
// code to be executed
} while (condition);
Example:
php
Copy code
<?php
$num = 2;
do {
$num += 2;
echo $num, "\n";
} while ($num < 12);
?>
Output:
Copy code
4
6
8
10
12
php
Copy code
foreach (array as $value)
{
// code to be executed
}
php
Copy code
<?php
$arr = array (10, 20, 30, 40, 50, 60);
foreach ($arr as $value)
Output:
Copy code
10
20
30
40
50
60
php
Copy code
<?php
$arr = array ("Ram", "Laxman", "Sita");
foreach ($arr as $value)
{
echo "$value \n";
}
?>
Output:
Copy code
Ram
Laxman
Sita
do-while loop Exit-Controlled When the block should execute at least once.
Iterative
foreach loop To iterate through array elements.
(Arrays)