0% found this document useful (0 votes)
27 views16 pages

JavaScript and PHP Code Examples

The document contains multiple HTML and JavaScript examples for creating forms and performing various calculations, such as validating user input, evaluating mathematical expressions, and calculating employee salaries. Additionally, it includes PHP scripts for generating prime numbers, Fibonacci series, and managing images in a database. Each section demonstrates different programming concepts and functionalities, suitable for educational purposes.

Uploaded by

Shelly Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views16 pages

JavaScript and PHP Code Examples

The document contains multiple HTML and JavaScript examples for creating forms and performing various calculations, such as validating user input, evaluating mathematical expressions, and calculating employee salaries. Additionally, it includes PHP scripts for generating prime numbers, Fibonacci series, and managing images in a database. Each section demonstrates different programming concepts and functionalities, suitable for educational purposes.

Uploaded by

Shelly Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Create a form with the elements of Textbox, Radio buttons, Checkboxes, and so
on.
Write JavaScript code to validate the format of email and mobile number. If any
textbox is left empty, display an alert indicating which field is missing.
<html>
<head>
<script>
function validation() {
var form = [Link]["myform"];
var name = form["name"].[Link]();
var email = form["email"].[Link]();
var mobile = form["mobileno"].[Link]();

var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/;


var mobileRegex = /^[0-9]{10}$/;

if (name === "") {


alert("Please enter your name");
return false;
}
if (![Link](email)) {
alert("Invalid email");
return false;
}
if (![Link](mobile)) {
alert("Invalid mobile number");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="myform" onsubmit="return validation()" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Mobile No: <input type="text" name="mobileno" maxlength="10"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
2. Develop an HTML Form, which accepts any Mathematical expression.
Write JavaScript code to evaluate the expression and display the result.
<head></head>
<body>
<form >
<html>
<label>Enter expression</label>
<input type="text" id="exp" name="exp">
<input type="button" value="calculate" onclick="k()">

<div id="result"></div>
</form>
<script type="text/javascript">
function k()
{
var i = [Link]("exp").value;
var x = eval(i);
[Link]("result").innerText = "output is" + x;
}
</script>
</body>
</html>
3. Create a page with dynamic effects.
Write the code to include layers and basic animation.
<!DOCTYPE html>
<html>
<head>
<title>Moving Text</title>
<style>
.layer {
position: absolute;
top: 150px;
left: 0;
background: skyblue;
padding: 10px 20px;
border-radius: 8px;
font-weight: bold;
}
</style>
</head>

<body>
<div id="move" class="layer">Web Programming</div>

<script>
let pos = 0, dir = 1;
setInterval(() => {
if (pos >= [Link] - 150 || pos <= 0) dir *= -1;
pos += 5 * dir;
[Link] = pos + "px";
}, 50);
</script>
</body>
</html>
4. Write a JavaScript code to find the sum of natural numbers.
(Use a user-defined function.)
<!DOCTYPE html>
<html>
<body>
Enter a number: <input id="num" type="number" min="1">
<button onclick="sum()">Calculate</button>
<p id="result"></p>

<script>
function sum() {
let n = +[Link]('num').value;
if (n < 1) {
[Link]('result').innerText = 'Enter a valid number.';
return;
}
let total = n * (n + 1) / 2;
[Link]('result').innerText = 'Sum is ' + total;
}
</script>
</body>
</html>
5. Write a JavaScript code block using arrays and generate the current date in
words, which should include the day, month, and year.
<!DOCTYPE html>
<html>
<body>
<h1>Today's Date</h1>
<p id="d"></p>
<script>
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"];
const months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const now = new Date();
const dn = days[[Link]()];
const mn = months[[Link]()];
const year = [Link]();
const date = [Link]();
const output = `${dn}, ${mn} ${date}, ${year}`;
[Link]("d").innerText = output;
</script>
</body>
</html>
6. Create a form for Student Information.
Write JavaScript code to find Total, Average, Result, and Grade.
<html>
<head>
<script>
function result() {
let name = [Link]("a1").value;
let a = +[Link]("m1").value;
let b = +[Link]("m2").value;
let c = +[Link]("m3").value;
let sum = a + b + c;
let avg = sum / 3;
let grade = avg >= 90 ? "A" : avg >= 75 ? "B" : avg >= 60 ? "C" : avg >=
40 ? "D" : "F";
[Link]("r1").innerText = "Name: " + name;
[Link]("r2").innerText = "Total Marks: " + sum;
[Link]("r3").innerText = "Average Marks: " +
[Link](2);
[Link]("r4").innerText = "Grade: " + grade;
}
</script>
</head>
<body>
Name: <input id="a1"><br>
Mark1: <input type="number" id="m1"><br>
Mark2: <input type="number" id="m2"><br>
Mark3: <input type="number" id="m3"><br>
<button onclick="result()">Calculate</button>
<p id="r1"></p>
<p id="r2"></p>
<p id="r3"></p>
<p id="r4"></p>
</body>
</html>
7. Create a form for Employee Information.
Write JavaScript code to find DA, HRA, PF, TAX, Gross Pay, Deduction, and Net
Pay.
<!DOCTYPE html>
<html>
<head>
<title>Employee Info & Salary Calculator</title>
<script>
function calculate() {
const basic = +[Link]("basic").value;
if (!basic || basic <= 0) {
alert("Enter a valid basic salary");
return;
}

const da = basic * 0.5; // 50%


const hra = basic * 0.1; // 10%
const gross = basic + da + hra;
const pf = gross * 0.12; // 12%
const tax = gross * 0.1; // 10%
const deduction = pf + tax;
const net = gross - deduction;

[Link]("da").value = [Link](2);
[Link]("hra").value = [Link](2);
[Link]("pf").value = [Link](2);
[Link]("tax").value = [Link](2);
[Link]("gross").value = [Link](2);
[Link]("deduction").value = [Link](2);
[Link]("net").value = [Link](2);
}
</script>
</head>
<body>
<h2>Employee Information & Salary Calculator</h2>
<form onsubmit="calculate(); return false;">
Name: <input type="text" id="name" required><br><br>
Basic Salary: <input type="number" id="basic" min="1" required><br><br>

DA: <input type="text" id="da" readonly><br><br>


HRA: <input type="text" id="hra" readonly><br><br>
PF: <input type="text" id="pf" readonly><br><br>
TAX: <input type="text" id="tax" readonly><br><br>
Gross Pay: <input type="text" id="gross" readonly><br><br>
Deduction: <input type="text" id="deduction" readonly><br><br>
Net Pay: <input type="text" id="net" readonly><br><br>
<button type="submit">Calculate</button>
</form>
</body>
</html>
8. Write a program in PHP to change background color based on day of the week
using if-else-if statements and using arrays.
<!DOCTYPE html>
<html>
<head>
<title>Color Change by Day</title>
<style>
<?php
$colors = [
"Sunday"=>"#FF5733","Monday"=>"#33FF57","Tuesday"=>"#3357FF",
"Wednesday"=>"#FFFF33","Thursday"=>"#FF33FF","Friday"=>"#33FFFF",
"Saturday"=>"#FF3333"
];
$day = date('l');
echo "body { background: {$colors[$day]}; text-align:center; font-family:Arial;
padding-top:100px; }";
?>
</style>
</head>
<body>
<h1>Welcome! Today is <?= $day ?>.</h1>
</body>
</html>
9. Write a simple program in PHP for:
i) Generating Prime Numbers
<?php
function generatePrimes($max) {
for ($num = 2; $num <= $max; $num++) {
$prime = true;
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
$prime = false;
break;
}
}
if ($prime) {
echo $num . " ";
}
}
echo "\n";
}

generatePrimes(50);
?>
ii) Generating Fibonacci Series
<?php
function fibonacciSeries($n) {
$a = 0;
$b = 1;
for ($i = 0; $i < $n; $i++) {
echo $a . " ";
$c = $a + $b;
$a = $b;
$b = $c;
}
echo "\n";
}

fibonacciSeries(10);
?>
[Link] a PHP program to remove duplicates from a sorted list.
<?php
function rd($a)
{
$result = array_values(array_unique($a));
return $result;
}

$sortedlist = [1, 1, 2, 2, 3, 3, 4, 5, 5];

echo "The list before removing duplicate values is:\n";


print_r($sortedlist);

$uniquelist = rd($sortedlist);

echo "The list after removing duplicate values is:\n";


print_r($uniquelist);
?>
[Link] a PHP Script to print the following pattern on the screen:
****
***
**
*
<?php

// Total number of rows for the pattern


$rows = 5;

for ($i = $rows; $i > 0; $i--) {


// Printing leading spaces
for ($j = $rows - $i; $j > 0; $j--) {
echo "&nbsp;"; // Non-breaking space for HTML output
}

// Printing asterisks
for ($k = 0; $k < $i; $k++) {
echo "*";
}

// Move to the next line


echo "<br>";
}

?>
[Link] a simple program in PHP for searching data by different criteria.
<?php
// Sample data array
$data = [
['id' => 1, 'name' => 'Srikanth', 'age' => 38],
['id' => 2, 'name' => 'Srinath', 'age' => 35],
['id' => 3, 'name' => 'Srinivas', 'age' => 50],
['id' => 4, 'name' => 'Smayan', 'age' => 45],
['id' => 5, 'name' => 'Saatvik', 'age' => 50]
];

// Function to search by criteria


function searchByCriteria($data, $criteria) {
$results = [];
foreach ($data as $entry) {
$match = true;
foreach ($criteria as $key => $value) {
if (!isset($entry[$key]) || $entry[$key] != $value) {
$match = false;
break;
}
}
if ($match) {
$results[] = $entry;
}
}
return $results;
}

// Search criteria
$criteria = ['age' => 50];

// Perform search
$results = searchByCriteria($data, $criteria);

// Display results
echo "<pre>";
print_r($results);
echo "</pre>";
?>
[Link] a function in PHP to generate CAPTCHA code.
<?php
session_start();

function ccode($length = 6)
{
$chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$charLen = strlen($chars);
$result = '';

for ($i = 0; $i < $length; $i++) {


$result .= $chars[rand(0, $charLen - 1)];
}

return $result;
}

echo "The captcha code is: " . ccode();


?>
[Link] a program to store and read an image from a database.
<?php
// Database connection
$conn = new mysqli("localhost", "root", "", "myDB"); // Update with your credentials

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// ✅ Display image when 'id' is passed


if (isset($_GET['id'])) {
$id = intval($_GET['id']);
$stmt = $conn->prepare("SELECT image_type, image_data FROM images WHERE id
= ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($imageType, $imageData);
$stmt->fetch();

header("Content-Type: $imageType");
echo $imageData;
exit;
}

// ✅ Handle image upload


if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
$imageName = $_FILES["image"]["name"];
$imageType = $_FILES["image"]["type"];
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);

$stmt = $conn->prepare("INSERT INTO images (image_name, image_type,


image_data) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $imageName, $imageType, $imageData);
$stmt->execute();
$stmt->close();
}

// Function to display uploaded images


function displayImages($conn)
{
$sql = "SELECT id, image_name FROM images";
$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {


echo '<img src="?id=' . $row["id"] . '" alt="' . $row["image_name"] . '"
width="200"><br>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload and Display</title>
</head>
<body>
<h1>Upload and Display Images</h1>

<form method="post" enctype="multipart/form-data">


Select image to upload:
<input type="file" name="image" id="image" required>
<input type="submit" value="Upload Image" name="submit">
</form>

<h2>Uploaded Images:</h2>
<?php displayImages($conn); ?>

<?php $conn->close(); ?>


</body>
</html>
[Link] a program in PHP to read and write file contents using file handling
functions.
<!DOCTYPE html>
<html>
<head><title>File Reader & Writer</title></head>
<body>
<h2>File Reader & Writer</h2>

<form method="post">
<textarea name="textdata" rows="4" cols="40" placeholder="Enter
text..."></textarea><br>
<input type="submit" name="write" value="Write to File">
</form><br>

<form method="post" enctype="multipart/form-data">


<input type="file" name="filedata">
<input type="submit" name="read" value="Read File">
</form><hr>

<?php
if (isset($_POST['write']) && !empty($_POST['textdata'])) {
file_put_contents("[Link]", $_POST['textdata']);
echo "✅ Data written to <b>[Link]</b><br>";
}
if (isset($_POST['read']) && !empty($_FILES['filedata']['tmp_name'])) {
echo "<pre>" .
htmlspecialchars(file_get_contents($_FILES['filedata']['tmp_name'])) . "</pre>";
}
?>
</body>
</html>
[Link] a PHP program to add, update and delete using student database
<?pup
$conn = new mysqli("localhost", "root", "", "abbsdb"); // Establish connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); // Connection error
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$regno = $_POST['regno'];
$name = $_POST['name'];
$age = $_POST['age'];
$course = $_POST['course'];

switch ($_POST['action']) {
case 'Add':
$sql = "INSERT INTO bcab VALUES ('$regno', '$name', '$age', '$course')";
break;
case 'Update':
$sql = "UPDATE bcab SET stname='$name', age='$age', department='$course'
WHERE uucmsno='$regno'";
break;
case 'Delete':
$sql = "DELETE FROM bcab WHERE uucmsno='$regno'";
break;
}

if ($conn->query($sql) === FALSE) {


echo "Error: " . $sql . "<br>" . $conn->error;
}
}

// Function to display students


function displayStudents($conn) {
$sql = "SELECT * FROM bcab";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table border='1'><tr><th>Reg
No</th><th>Name</th><th>Age</th><th>Course</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["uucmsno"] . "</td><td>" . $row["stname"] .
"</td><td>" . $row["age"] . "</td><td>" . $row["department"] . "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Student Database Management</title>
</head>
<body>
<h1>BCA Students</h1>
<form method="post">
Reg No: <input type="text" name="regno" required><br><br>
Name: <input type="text" name="name"><br><br>
Age: <input type="number" name="age"><br><br>
Course: <input type="text" name="course"><br><br>
<input type="submit" name="action" value="Add">
<input type="submit" name="action" value="Update">
<input type="submit" name="action" value="Delete">
</form>

<?php
displayStudents($conn); // Display students
$conn->close(); // Close connection
?>
</body>
</html>
[Link] a PHP program to validate input
<!DOCTYPE html>
<html>
<head>
<title>Input Validations</title>
</head>
<body>
<form method="post" action="">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);

if (empty($name)) {
echo "Name is required.<br>";
} else {
echo "Name: " . htmlspecialchars($name) . "<br>";
}

if (empty($email)) {
echo "Email is required.<br>";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.<br>";
} else {
echo "Email: " . htmlspecialchars($email) . "<br>";
}
}
?>
</body>
</html>
[Link] a program in php for seting and retrieving a cookie
<!DOCTYPE html>
<html>
<head>
<title>Cookie Handler</title>
</head>
<body>
<?php
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
!empty($_POST['username'])) {
setcookie("username", $_POST['username'], time() + 3600, "/"); // valid for 1 hour
echo "<p>✅ Cookie set. Reload the page to see the cookie value.</p>";
}

// Display cookie value if it exists


if (isset($_COOKIE["username"])) {
echo "<p>Welcome back, <b>" . htmlspecialchars($_COOKIE["username"]) .
"</b>!</p>";
} else {
echo "<p>Welcome, guest!</p>";
}
?>
<hr>
<form method="post" action="">
<label for="username">Enter your name:</label><br>
<input type="text" id="username" name="username" required>
<input type="submit" value="Set Cookie">
</form>
</body>
</html>
[Link] a PHP program to create a simple webpage of your college.
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to ABC College</title>
</head>
<body>
<h1>Welcome to ABC College</h1>
<p>Select a page:</p>
<ul>
<li><a href="[Link]">Home</a></li>
<li><a href="[Link]">Courses</a></li>
<li><a href="[Link]">Contact</a></li>
</ul>
</body>
</html>
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home - ABC College</title>
</head>
<body>
<h1>Home - ABC College</h1>
<p>ABC College is committed to providing quality education and shaping
future leaders.</p>
<p><a href="[Link]">Back to Index</a></p>
</body>
</html>
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Courses - ABC College</title>
</head>
<body>
<h1>Our Courses</h1>
<ul>
<?php
$courses = ["[Link] Computer Science", "[Link]", "B.A English", "MBA",
"[Link] Data Science"];
foreach ($courses as $course) {
echo "<li>$course</li>";
}
?>
</ul>
<p><a href="[Link]">Back to Index</a></p>
</body>
</html>
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact - ABC College</title>
</head>
<body>
<h1>Contact Us</h1>
<p>Email: info@[Link]</p>
<p>Phone: +91 12345 67890</p>
<p><a href="[Link]">Back to Index</a></p>
</body>
</html>
[Link] a program in PHP for exception handling for:
a) Divide by zero
<?php
function divide($a, $b) {
if ($b == 0) {
throw new Exception("Cannot divide by zero.");
}
return $a / $b;
}

try {
echo "Result: " . divide(10, 2) . "<br>"; // OK
echo "Result: " . divide(10, 0) . "<br>"; // Error
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
b) Checking date format
<?php
function checkDateFormat($date, $format = 'Y-m-d') {
$dt = DateTime::createFromFormat($format, $date);
if (!$dt || $dt->format($format) !== $date) {
throw new Exception("Invalid date format.");
}
echo "Valid date: $date";
}

try {
checkDateFormat("2023-10-12"); // OK
checkDateFormat("12/10/2023"); // Error
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>

You might also like