0% found this document useful (0 votes)
3 views

cat2

The document provides a comprehensive answer key for a web essentials exam covering JavaScript and PHP. It includes benefits of JavaScript, client-side scripting necessity, JavaScript objects, types of statements, and examples of coding in both JavaScript and PHP. Additionally, it explains server-side processing in PHP, file uploading, and sending emails using PHP's mail function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

cat2

The document provides a comprehensive answer key for a web essentials exam covering JavaScript and PHP. It includes benefits of JavaScript, client-side scripting necessity, JavaScript objects, types of statements, and examples of coding in both JavaScript and PHP. Additionally, it explains server-side processing in PHP, file uploading, and sending emails using PHP's mail function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

22IT005-WEB ESSENTIALS

CAT 2-ANSWER KEY


PART A
1.What is the benefits of using Javascript code in a HTML document?
● The client side data validation can be possible using JavaScript
● We can access the HTML element. that means we can have control over HTML, body, title
tags.
● JavaScript can determine the visitor’s browser and can load the page accordingly.
2.Why is client side scripting necessary?
● Simple scripting language like HTMLor XML represents the data on the webpage in simplest
manner.
● The scripting language like JavaScript and DHTML are useful for enhancing the interactivity
of the user with the web browser.
● Mathematical evaluation is also possible using the client side scripting .
● The input validation can also possible using client side scripting language like JavaScript .
● Using cascading stylesheet with client scripts the look and feel of the webpage can be
enhanced.
3. List out the object used in JavaScript with its purpose.
● Math object -this object provides useful methods that are required for mathematical
competition
example: for computing square root of some numbers sqrt (number) method is used.
● Number object the object is used for various Numerical properties.
example: largest possible number gets displayed using MAX_VALUE.
● Date object this object is used for obtaining date and time.
for example: using get time function the number of milliseconds can be obtained
● Boolean object- this is the simplest object used to apply true or false values.
● String object -this object provides many useful string related functionalities.
for example -string length used to find length of the string .
4.Take the types of JavaScript statement with example.

● simple assignment statements-var a=23;


● conditional statements -if,else
● object manipulation statements-var a=34;
● comment statements-//comment
● exception handling statements-try,catch

5.Write a JavaScript to print good day using if else condition

<html>
<head>
<script>
function MyMessage(){
var today=new Date();
var h= today. getHours();
if(h<12) document. write(“ Good Day”);
else document.write(“ Good Bye”);
}</ script>
</ head>
<body onload=”MyMessage()”>
</ body>
</html>

6.what is PHP stands for?

PHP stands for “Hypertext Preprocessor”. It is widely used open-source scripting language primarily
designed for web development.

7.How can a PHP program determine the types of browser that a web client is using?

<?php
echo $_SERVER[‘HTTP_USER_AGENT’];
$ browser= get_Browser();
print_r($browser);
?>
8.How do you declare a variable in PHP?

In PHP, variables are declared using $ sign followed by variable name. PSP automatically determines
the variable type based on a value assign to it( dynamic typing).
example:
<?php
$var1=” hello”;//string
$var2=12;//num
$var2=12.2;//Float
?>
9. Name any two types of loops available in PHP.
1. For loop use when you know the number of iterations.
<?php
for($i=0;$i<5;$i++){
echo”the value of i is $i<br>”;
}

?>

2. while loop used when the number of hydration is unknown and its run as long as a condition is true.

<?php

$i=0;

while($i<5){

echo”The valu of i is $i,br>”;

$i++;

?>

10.Write a simple PHP script to display “Hello, World!”.

<?php

echo”Hello, World!”;

?>

PART B

1 a)i)Explain the types of statement with an example in JavaScript.

1. Simple Assignment Statements:


These statements are used to assign values to variables using the = operator.

Example:

var a = 23; // Assigning the value 23 to the variable 'a'

2. Conditional Statements :

Conditional statements allow you to make decisions in your code based on certain conditions. The
common ones are if, else if, and else.

Example:

var age = 18;

if (age >= 18) {

console.log("You are an adult.");

} else {

console.log("You are a minor.");

3. Object Manipulation Statements:

In JavaScript, objects are manipulated by assigning properties or methods to them or modifying their
values.

Example:

var person = {

name: "John",

age: 30

};

person.age = 34; // Updating the age property of the 'person' object

console.log(person.age); // Output: 34
4. Comment Statements :

Comments are non-executable statements used to add notes to the code. They are ignored by the
JavaScript engine.

Example:

// This is a single-line comment

var x = 10; // This is another comment

/*

This is a multi-line comment

which spans multiple lines.

*/

5. Exception Handling Statement:

Exception handling allows you to catch and handle errors gracefully using the try...catch block.

Example:

try {

let result = 10 / 0;

console.log(result); // Outputs: Infinity

} catch (error) {

console.log("An error occurred: " + error.message);

ii) Write a JavaScript program that generates a random number between 1 and 100 using the
Math object.

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Random Number Generator</title>

</head>

<body>

<h1>Random Number between 1 and 100</h1>

<p id="randomNumber"></p>

<script>

// Generate a random number between 1 and 100

let randomNumber = Math.floor(Math.random() * 100) + 1;

// Display the random number in the paragraph element

document.getElementById("randomNumber").innerText = "Generated Random Number: " +


randomNumber;

</script>

</body>

</html>

OR

11 b)i)Explain how functions can be written in JavaScript with an example.

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it)

.JavaScript Function Syntax


1. A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
2. Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
3. The parentheses may include parameter names separated by commas:
4. (parameter1, parameter2, ...)
5. The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {

// code to be executed

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

● When an event occurs (when a user clicks a button)


● When it is invoked (called) from JavaScript code
● Automatically (self invoked)

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Example:
<!DOCTYPE html>

html>

<body>

<h1>JavaScript Functions</h1>

<p>Call a function which performs a calculation and returns the result:</p>

<p id="demo"></p>

<script>

let x myFunction (4, 3);

document.getElementById("demo").innerHTMLx;

function myFunction(a, b) [ return wb;

</script>

</body>

</html>

Output:

JavaScript Functions

Call a function which performs a calculation and returns the result:

12

Use of function:

● With functions you can reuse code


● You can write code that can be used many times.
● You can use the same code with different arguments, to produce different results.
The () Operator

The () operator invokes (calls) the function:

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and
calculation.

Example:

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Functions</h1>

<p>Using a function as variable:</p>

<p. id-"demo"></p>

Let text "The temperature 15" toCelsius(77) document.getElementById("demo").innerHTML text;


Celsius.";

<script>

function toCelsius (fahrenheit) { return (5/9) (fahrenheit-32):

} </script>

</body>

</html>

Output:

JavaScript Functions

Using a function as a variable:

The temperature is 25 Celsius.


ii) write a javascript program that lessons for a button click and changes the background
colour of a webpage.

<!DOCTYPE html>

<html>

<head>

<title>Change Background Color</title>

</head>

<body>

<button id="colorButton">Change Background Color</button>

<script>

document.getElementById("colorButton").addEventListener("click", function() {

document.body.style.backgroundColor = "lightblue";

});

</script>

</body>

</html>

12 a)i) Explain how PHP works on a server side with an example.

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development.
When a client (like a browser) requests a PHP page, here’s the process that happens:

1. Client Request: The user sends a request to the server, such as entering a URL in the browser or
submitting a form.

2. Server Processing: The web server (such as Apache or Nginx) receives the request and forwards it
to the PHP interpreter.

3. PHP Script Execution: The PHP interpreter processes the PHP code on the server. It can interact
with databases, handle files, process forms, etc.
4. HTML Output: After processing, PHP generates HTML (or other types of content) which is sent
back to the client’s browser as the response.

5. Client Display: The browser displays the HTML content, but the actual PHP code is not visible to
the client because it's executed on the server.

Example Workflow:

1. A client visits a URL like http://example.com/index.php.

2. The server detects the .php extension and runs the script via the PHP engine.

3. The PHP code inside index.php is processed and converted to HTML.

4. The server sends the HTML response back to the client’s browser, which displays the result.

Example of a Simple PHP Script:

<?php

// This is server-side code. The client will only see the HTML output.

echo "Hello, World! This is generated by PHP.";

?>

In the browser, the output would be:

Hello, World! This is generated by PHP.

ii) Write a program that accepts user input and display it using PHP variables.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>User Input in PHP</title>


</head>

<body>

<h1>Enter Your Details</h1>

<!-- HTML Form to collect user input -->

<form method="POST" action="">

Name: <input type="text" name="name" required><br><br>

Age: <input type="number" name="age" required><br><br>

<input type="submit" value="Submit">

</form>

<?php

// Checking if form data is submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = $_POST['name'];

$age = $_POST['age'];

// Displaying the input values

echo "<h2>Your Input:</h2>";

echo "Name: " . $name . "<br>";

echo "Age: " . $age;

?>

</body>
</html>

OR

12b)i) Explain the process of file uploading in PHP and demonstrate it with examples.

PHP File Upload

PHP allows you to upload single and multiple files through few lines of code only.PHP file upload
features allows you to upload binary and text files both. Moreover, you can have the full control over
the file to be uploaded through PHP authentication and file operation functions.

PHP $_FILES

The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can
get file name, file type, file size, temp file name and errors associated with file.Here, we are assuming
that file name is filename.

1. $_FILES['filename']['name']-returns file name.


2. $_FILES['filename']['type']-returns MIME type of the file.
3. $_FILES['filename']['size']-returns size of the file (in bytes).
4. $_FILES['filename']['tmp_name']-returns temporary file name of the file which was stored on
the server.
5. $_FILES['filename']['error']-returns error code associated with this file.

move_uploaded_file() function

The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST request. It
moves the file if it is uploaded through the POST request.

Syntax

bool move_uploaded_file ( string $filename , string $destination )

PHP File Upload Example

<?php

$target_dir = "uploads/";

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if image file is a actual image or fake image

if(isset($_POST["submit"])) {

$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);

if($check !== false) {

echo "File is an image - " . $check["mime"] . ".";

$uploadOk = 1;

} else {

echo "File is not an image.";

$uploadOk = 0;

// Check if file already exists

if (file_exists($target_file)) {

echo "Sorry, file already exists.";

$uploadOk = 0;

// Check file size

if ($_FILES["fileToUpload"]["size"] > 500000) {

echo "Sorry, your file is too large.";


$uploadOk = 0;

// Allow certain file formats

if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"

&& $imageFileType != "gif" ) {

echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";

$uploadOk = 0;

// Check if $uploadOk is set to 0 by an error

if ($uploadOk == 0) {

echo "Sorry, your file was not uploaded.";

// if everything is ok, try to upload file

} else {

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been
uploaded.";

} else {

echo "Sorry, there was an error uploading your file.";

?>

ii)Write a PHP script that sends a simple email using mail()function.


<?php
// Email recipient
$to = "[email protected]";
// Subject of the email
$subject = "Simple Mail Test";
// Message content
$message = "This is a simple test email sent using PHP's mail function.";
// Additional headers (optional)
$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
// Sending the email
if(mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>

You might also like