Friday, 10 January 2025

BCA Scripting Language 4th Semester

Scripting Language Concepts Quiz



1. Client Side Scripting :


1. Client-Side Scripting (15 hrs)

JavaScript: Introduction, Need of Client-Side Scripting Language, and Related Concepts

Introduction:

  • JavaScript is a lightweight, interpreted, or just-in-time compiled programming language. It is primarily used for adding interactivity to web pages, enabling client-side scripting on the user's browser.
  • JavaScript can manipulate the DOM (Document Object Model), handle events, validate forms, and create animations, among other things.

Need of Client-Side Scripting Language:

  • Enhanced User Experience: Client-side scripting languages like JavaScript enable interactive web pages. For instance, you can modify the content of the webpage dynamically without needing to reload the page.
  • Performance: By moving processing to the client (browser), JavaScript reduces server load and speeds up the response time of the application.
  • Cross-Platform Compatibility: JavaScript runs on almost all browsers and platforms, providing universal compatibility.
  • Asynchronous Operations: JavaScript can handle asynchronous operations (e.g., loading content in the background) using technologies like AJAX, which helps in creating dynamic and faster web applications.

Formatting and Coding Conventions:

Adhering to formatting and coding conventions ensures that the code is clean, readable, and maintainable. Some common conventions are:

  • Indentation: Use consistent indentation (e.g., 2 spaces or 4 spaces per level) for better readability.
  • Naming Conventions: Use camelCase for variable and function names (e.g., myFunction, userData).
  • Comments: Use comments to describe your code for others and yourself.

JavaScript Files:

  • External JavaScript Files: To maintain clean code and improve performance, JavaScript is often written in external files and linked to HTML files using the <script> tag.

    Example:

    <script src="script.js"></script>
    

Comments in JavaScript:

  • Single-line comments start with //.
  • Multi-line comments are enclosed between /* and */.
// This is a single-line comment

/* 
This is a 
multi-line comment
*/

Embedding JavaScript in HTML:

JavaScript can be embedded directly within an HTML document using the <script> tag.

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Example</title>
</head>
<body>

  <h1>Welcome to JavaScript</h1>
  
  <script>
    alert("Hello, world!");
  </script>

</body>
</html>

Using the <script> Tag:

  • The <script> tag is used to embed JavaScript code within an HTML document. It can be placed in the <head> or <body> section.
  • JavaScript code in the <head> is loaded before the body, while JavaScript in the <body> is executed after the content is loaded.
<script>
  console.log("This is a message.");
</script>

NoScript Tag:

  • The <noscript> tag is used to provide alternative content for users who have JavaScript disabled in their browsers.
<noscript>
  <p>Your browser does not support JavaScript or it is disabled.</p>
</noscript>

Operators in JavaScript:

Operators are symbols that perform operations on variables or values.

  • Arithmetic Operators: Used to perform mathematical operations.
    • + (addition), - (subtraction), * (multiplication), / (division), % (modulus)
let x = 10;
let y = 5;
console.log(x + y);  // Output: 15
  • Comparison Operators: Used to compare values.
    • == (equal to), != (not equal), > (greater than), < (less than), >= (greater than or equal to)
console.log(5 == 5);  // true
console.log(5 != 10); // true
  • Logical Operators: Used to combine conditions.
    • && (AND), || (OR), ! (NOT)
let a = true, b = false;
console.log(a && b); // false

Control Structures in JavaScript:

Control structures dictate the flow of the program.

  • If-Else Statement: A conditional structure that executes code based on a condition.
let age = 18;
if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}
  • Switch-Case: A control structure that evaluates an expression and matches it with different cases.
let fruit = "apple";
switch (fruit) {
  case "apple":
    console.log("It's an apple.");
    break;
  case "banana":
    console.log("It's a banana.");
    break;
  default:
    console.log("Unknown fruit.");
}
  • Loops (For, While, Do-While): Used for repeated execution.
// For loop
for (let i = 0; i < 5; i++) {
  console.log(i); // Outputs numbers from 0 to 4
}

// While loop
let j = 0;
while (j < 5) {
  console.log(j); // Outputs numbers from 0 to 4
  j++;
}

Array and forEach Loop:

An array is a special variable that can store multiple values. JavaScript arrays are zero-indexed.

let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // Outputs: apple

The forEach loop allows you to iterate through array elements.

fruits.forEach(function(fruit) {
  console.log(fruit);  // Outputs each fruit in the array
});

Defining and Invoking Functions:

Functions allow you to define reusable blocks of code.

// Function declaration
function greet(name) {
  console.log("Hello, " + name);
}

// Function invocation
greet("Alice");  // Output: Hello, Alice

Built-in Objects in JavaScript:

JavaScript provides various built-in objects like Date, Math, and String to perform specific tasks.

  • Date Object: Used to handle date and time.
let today = new Date();
console.log(today);  // Outputs current date and time
  • Math Object: Provides mathematical functions.
console.log(Math.random()); // Outputs a random number between 0 and 1
console.log(Math.max(1, 2, 3)); // Outputs 3

Date Objects in JavaScript:

The Date object is used to represent dates and times.

let currentDate = new Date();
console.log(currentDate.getFullYear());  // Outputs the current year

Interacting With the Browser:

JavaScript can interact with the browser using the window object and manipulate browser features.

// Alert box
window.alert("This is an alert");

// Prompt box to collect user input
let userInput = window.prompt("Enter your name:");
console.log(userInput);  // Outputs the name entered by the user

Windows and Frames in JavaScript:

JavaScript allows interaction with browser windows and frames.

// Opening a new window
let newWindow = window.open("https://www.example.com", "exampleWindow", "width=600,height=400");

Document Object Model (DOM):

The DOM represents the structure of an HTML document as an object. JavaScript interacts with this structure, allowing you to manipulate HTML and CSS dynamically.

document.getElementById("header").innerHTML = "New Header Text";  // Changes the content of an element with id 'header'

Event Handling in JavaScript:

JavaScript can handle events like clicks, keypresses, and mouse movements.

<button onclick="changeText()">Click me</button>

<script>
  function changeText() {
    document.getElementById("header").innerHTML = "Button Clicked!";
  }
</script>

Events can also be handled using Event Listeners:

document.getElementById("myButton").addEventListener("click", function() {
  alert("Button clicked!");
});

Forms and Client-Side Validations:

Forms are essential for collecting user input. JavaScript can validate form fields before submitting them.

<form id="myForm">
  <input type="text" id="name" placeholder="Enter your name" required>
  <input type="submit" value="Submit">
</form>

<script>
  document.getElementById("myForm").onsubmit = function() {
    let name = document.getElementById("name").value;
    if (name === "") {
      alert("Name is required!");
      return false;  // Prevent form submission
    }
  };
</script>

Cookies in JavaScript:

Cookies are small pieces of data stored on the client-side. JavaScript can create, read, and delete cookies.

// Create a cookie
document.cookie = "username=John Doe; expires=Fri, 31 Dec 2025 23:59:59 GMT";

// Read cookies

Server Side Scripting with Database Connectivity

Server Side Scripting with Database Connectivity: Detailed Notes

1. PHP (8 Hours)

PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed for web development but also used as a general-purpose language. PHP is especially known for its ability to interact with databases and is integral in building dynamic and interactive websites.

a. Introduction to Server-Side Scripting Language

Server-side scripting involves scripts executed on the server, where the server processes the code and sends the result to the client's browser. PHP is one of the most popular languages for server-side scripting. It allows developers to create dynamic web pages by embedding code into HTML. Server-side scripting processes user input, accesses databases, sends emails, and more.

b. Basic PHP Syntax

  • PHP Code Structure: PHP code is written between <?php and ?>.
    <?php
      echo "Hello, World!";
    ?>
    
  • Statements: Each PHP statement ends with a semicolon.
  • Variables: PHP variables are prefixed with a dollar sign ($), followed by the variable name (e.g., $variable).
    $name = "John Doe";
    

c. Comments in PHP

PHP supports both single-line and multi-line comments.

  • Single-line comment:
    // This is a single-line comment
    
  • Multi-line comment:
    /* This is a multi-line comment
       that spans more than one line */
    

d. Variables in PHP

Variables in PHP are loosely typed, meaning the variable's data type is determined at runtime.

  • Declaring a variable:
    $name = "Alice";  // string
    $age = 30;        // integer
    

e. PHP Operators

PHP provides several operators:

  • Arithmetic operators: +, -, *, /, %
  • Comparison operators: ==, ===, !=, >, <, >=, <=
  • Logical operators: &&, ||, !
  • Assignment operators: =, +=, -=, *=, /=

f. Control Structures

Control structures in PHP allow us to control the flow of execution based on conditions and loops.

  • If-Else:
    if ($age > 18) {
        echo "Adult";
    } else {
        echo "Minor";
    }
    
  • Switch:
    switch($day) {
        case 1:
            echo "Monday";
            break;
        case 2:
            echo "Tuesday";
            break;
        default:
            echo "Unknown day";
    }
    
  • Loops:
    • For Loop:
      for ($i = 0; $i < 5; $i++) {
          echo $i;
      }
      
    • While Loop:
      while ($i < 5) {
          echo $i;
          $i++;
      }
      
    • For Each Loop:
      $fruits = ["Apple", "Banana", "Cherry"];
      foreach ($fruits as $fruit) {
          echo $fruit;
      }
      

g. Functions

Functions allow for reusable blocks of code. In PHP, a function is declared using the function keyword.

function greet($name) {
    echo "Hello, $name!";
}
greet("Alice");

h. Form Handling

PHP is commonly used to process form data. Forms in HTML are submitted to PHP scripts via the POST or GET methods.

  • $_GET: Used to collect form data after submission via the GET method.
    $name = $_GET['name'];
    
  • $_POST: Used to collect form data after submission via the POST method.
    $name = $_POST['name'];
    

i. PHP $_GET, $_POST, and $_REQUEST

  • $_GET: Collects data sent via URL query strings (GET method).
  • $_POST: Collects data sent via HTTP POST method.
  • $_REQUEST: A superglobal array that combines data from both $_GET and $_POST.

j. PHP date() Function

The date() function formats a local date/time based on a specific format.

echo date("Y-m-d H:i:s");  // Outputs: 2025-01-11 15:30:00

k. PHP Include Files

PHP allows you to include external PHP files using include or require.

include('header.php');

l. File Handling

PHP allows you to read and write to files using functions like fopen(), fread(), and fwrite().

$file = fopen("test.txt", "r");
$content = fread($file, filesize("test.txt"));
fclose($file);

m. File Uploading

PHP allows users to upload files through a form.

if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    move_uploaded_file($file['tmp_name'], 'uploads/' . $file['name']);
}

n. PHP Sessions

Sessions are used to store information about a user during their visit to a website. Session data is stored on the server.

session_start();
$_SESSION['username'] = 'john_doe';

o. Sending Emails in PHP

PHP provides the mail() function to send emails.

mail("example@example.com", "Subject", "Message", "From: sender@example.com");

p. PHP Cookies

Cookies are small pieces of data stored on the client’s browser.

setcookie("user", "John Doe", time() + 3600);  // Cookie expires in 1 hour

2. MySQL (7 Hours)

MySQL is a relational database management system. It uses structured query language (SQL) for managing and querying data stored in tables.

a. Introduction to MySQL

MySQL is a widely used, open-source database system designed to store and manage data in a relational format. It supports SQL queries to interact with the data and is often used with PHP in web applications.

b. PHP MySQL Connect to a Database

To interact with a MySQL database from PHP, we first need to establish a connection using the mysqli_connect() function:

$connection = mysqli_connect("localhost", "username", "password", "database_name");

c. Closing a Connection

To close the database connection, we use the mysqli_close() function:

mysqli_close($connection);

d. MySQL Data Types

MySQL supports several data types:

  • INT: Integer values
  • VARCHAR: Variable-length strings
  • TEXT: Long text data
  • DATE: Date values
  • FLOAT: Floating-point numbers

e. MySQL Insert Statement

To insert data into a table, the INSERT INTO statement is used.

$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
mysqli_query($connection, $sql);

f. MySQL Select Statement

To retrieve data from a table, use the SELECT statement.

$sql = "SELECT * FROM users";
$result = mysqli_query($connection, $sql);

g. MySQL WHERE Clause

The WHERE clause is used to filter records.

$sql = "SELECT * FROM users WHERE age > 18";

h. MySQL Delete Statement

To delete records from a table, use the DELETE statement.

$sql = "DELETE FROM users WHERE id = 1";
mysqli_query($connection, $sql);

i. MySQL Update Statement

To update records in a table, the UPDATE statement is used.

$sql = "UPDATE users SET age = 30 WHERE id = 1";
mysqli_query($connection, $sql);

j. MySQL Aggregate Functions

MySQL includes aggregate functions such as:

  • SUM(): Adds up values
  • AVG(): Returns the average value
  • COUNT(): Counts the number of rows
$sql = "SELECT COUNT(*) FROM users";
$result = mysqli_query($connection, $sql);

k. MySQL Order By and Group By Clauses

  • ORDER BY: Sorts the result set.
    $sql = "SELECT * FROM users ORDER BY age DESC";
    
  • GROUP BY: Groups rows sharing the same values.
    $sql = "SELECT age, COUNT(*) FROM users GROUP BY age";
    

l. MySQL Subqueries

A subquery is a query inside another query. It can be used in SELECT, INSERT, UPDATE, or DELETE statements.

$sql = "SELECT name FROM users WHERE age = (SELECT MAX(age) FROM users)";

m. MySQL Joins

Joins are used to combine data from two or more

tables.

  • INNER JOIN: Returns rows that have matching values in both tables.
    $sql = "SELECT * FROM orders INNER JOIN users ON orders.user_id = users.id";
    


3. Advanced Server Side Scripting :

Advanced Server-Side Scripting: Detailed Notes (15 Hours)

1. Object-Oriented Programming (OOP) in PHP (7 Hours)

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects," which can contain data (properties) and code (methods). PHP fully supports OOP, and understanding its principles is crucial for building scalable and maintainable web applications.

a. Classes and Objects

  • Class: A class is a blueprint for creating objects (instances). It defines properties (attributes) and methods (functions) that the objects will have.

    class Car {
        public $color;
        public $model;
        
        public function start() {
            echo "Car started";
        }
    }
    
    // Creating an object (instance) of the Car class
    $myCar = new Car();
    $myCar->color = "Red";
    $myCar->model = "Toyota";
    $myCar->start();
    
  • Object: An object is an instance of a class. Each object can hold specific values for its properties.

    $car1 = new Car();
    $car2 = new Car();
    

b. Defining and Using Properties and Methods

  • Properties: Variables that belong to the class. They define the attributes of an object.

    class Car {
        public $color;
        public $brand;
    }
    
  • Methods: Functions that define the behavior of an object. They are defined within a class.

    class Car {
        public function start() {
            echo "Car started";
        }
    }
    

c. Constructors and Destructors

  • Constructor: A special method that is automatically called when an object is created. It is used to initialize the properties of an object.

    class Car {
        public $color;
        public $brand;
    
        public function __construct($color, $brand) {
            $this->color = $color;
            $this->brand = $brand;
        }
    }
    $car = new Car("Red", "Toyota");
    
  • Destructor: A special method that is automatically called when an object is destroyed. It is used to clean up any resources.

    class Car {
        public function __destruct() {
            echo "Object destroyed";
        }
    }
    

d. Method Overriding

Method overriding is a feature that allows a subclass to provide a specific implementation of a method that is already defined in its parent class.

class Vehicle {
    public function start() {
        echo "Vehicle started";
    }
}

class Car extends Vehicle {
    public function start() {
        echo "Car started";
    }
}

$car = new Car();
$car->start();  // Outputs: Car started

e. Encapsulation

Encapsulation refers to the concept of restricting direct access to some of an object's components. It is usually implemented by making properties private or protected and accessing them via getter and setter methods.

class Car {
    private $color;

    public function setColor($color) {
        $this->color = $color;
    }

    public function getColor() {
        return $this->color;
    }
}

$car = new Car();
$car->setColor("Red");
echo $car->getColor();  // Outputs: Red

f. Inheritance

Inheritance allows a class to inherit properties and methods from another class. This promotes code reusability and establishes a relationship between classes.

class Vehicle {
    public function drive() {
        echo "Driving";
    }
}

class Car extends Vehicle {
    public function honk() {
        echo "Honk!";
    }
}

$car = new Car();
$car->drive();  // Outputs: Driving
$car->honk();   // Outputs: Honk!

g. Polymorphism

Polymorphism allows methods to have the same name but behave differently depending on the object calling them. It can be achieved through method overriding or method overloading.

class Animal {
    public function sound() {
        echo "Some sound";
    }
}

class Dog extends Animal {
    public function sound() {
        echo "Bark";
    }
}

$dog = new Dog();
$dog->sound();  // Outputs: Bark

h. Static Members

Static members belong to the class itself rather than any particular object. They can be accessed without creating an instance of the class.

class Car {
    public static $brand = "Toyota";

    public static function displayBrand() {
        echo self::$brand;
    }
}

Car::displayBrand();  // Outputs: Toyota

i. Exception Handling

Exception handling in PHP is done using try, catch, and throw. It is used to handle errors gracefully by catching exceptions and providing a way to recover or report them.

try {
    $num = 10 / 0;  // Division by zero
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();  // Outputs: Error: Division by zero
}

2. AJAX (Asynchronous JavaScript and XML) (3 Hours)

AJAX is a technique for creating asynchronous web applications. It allows a web page to send data to and receive data from a server asynchronously without refreshing the page.

a. Using PHP with AJAX

  • AJAX Request: JavaScript sends an AJAX request to the server using XMLHttpRequest or fetch.

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "data.php", true);
    xhr.send();
    
    xhr.onload = function() {
        if (xhr.status == 200) {
            document.getElementById("result").innerHTML = xhr.responseText;
        }
    }
    
  • PHP Processing: PHP processes the request and sends a response back to the browser.

    <?php
    echo "Data received successfully";
    ?>
    

b. Using PHP with MySQL in AJAX

AJAX can be used with PHP and MySQL to fetch or submit data to a database without page refresh.

var xhr = new XMLHttpRequest();
xhr.open("GET", "fetch_data.php", true);
xhr.send();
// fetch_data.php
$connection = mysqli_connect("localhost", "username", "password", "database");
$result = mysqli_query($connection, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . "<br>";
}

3. jQuery (3 Hours)

jQuery is a fast, small, and feature-rich JavaScript library that makes HTML document traversal, event handling, and animation easy.

a. Playing with Elements

jQuery simplifies DOM manipulation, allowing easy interaction with HTML elements:

$("#elementId").text("New Text");
$("#elementId").css("color", "red");

b. Hiding and Unhiding Elements

You can hide and show elements using jQuery:

$("#elementId").hide();  // Hides the element
$("#elementId").show();  // Shows the element

c. jQuery UI

jQuery UI is a collection of GUI widgets, effects, and themes built on top of jQuery. It allows for easy customization and interaction in web applications.

  • Accordion: Creates collapsible panels.

    $( "#accordion" ).accordion();
    
  • Datepicker: Allows the user to select a date from a calendar.

    $( "#datepicker" ).datepicker();
    

4. Joomla (5 Hours)

Joomla is a powerful open-source content management system (CMS) for creating websites and web applications.

a. Introduction to Joomla CMS

Joomla is a user-friendly CMS that allows you to build dynamic websites. It is written in PHP and uses MySQL for database storage.

b. Installation and Handling Joomla Backend

Joomla can be installed on any server supporting PHP and MySQL. After installation, administrators can log into the backend to manage content, users, templates, and more.

c. Customization in Joomla

Joomla allows extensive customization, including themes, templates, and plugins. It is ideal for building both simple and complex websites.

d. Introduction to Joomla Extensions

Joomla extensions are modules, components, and plugins that extend the functionality of the website.

  • Modules: Small content blocks displayed on pages (e.g., menus, search bars).
  • Components: Larger functional pieces that serve as the main content (e.g., contact forms, e-commerce).
  • Plugins: Enhance the functionality of specific features in Joomla.

e. Template Development in Joomla

Templates define the layout and appearance of a Joomla website. Joomla supports custom template development using HTML, CSS, and PHP.

f. Artiseer (IDE)

Artiseer is a popular integrated development environment (IDE) for Joomla template development. It allows designers to create Joomla templates with a WYSIWYG (What You See Is What You Get) interface.

g. Module and Component Development in Joomla

  • Modules: Can be created to display content in positions like sidebars or headers.
  • Components: Joomla components handle specific features and functionalities, like managing user accounts or

creating a blog.

h. MVC (Model-View-Controller)

Joomla uses the MVC architecture to separate the data (Model), the presentation (View), and the control flow (Controller). This separation promotes better organization, maintenance, and scalability.



Syllabus

Course Description

Course Description

This course includes both theoretical as well as practical knowledge of scripting language (client side & server side) along with database connectivity. So that students can develop more effective and efficient web based application packages.

Course Objectives

The general objectives of this course are to provide fundamental concepts of server side script programming and client side script programming using JavaScript and PHP respectively along with database connectivity.

 Unit Contents

1. Client Side Scripting  : 15 hrs

JavaScript: Introduction, Need of Client Side Scripting Language, Formatting and Coding Conventions, JavaScript Files, Comments, Embedding JavaScript in HTML, Using Script Tag, NoScript Tag, Operators, Control Structures, Array and For Each Loop, Defining and Invoking Functions, Built in Objects, Date Objects, Interacting With The Browser, Windows & Frames, Document Object  Model, Event Handling, Forms, Cookies, Handling Regular Expression, Client Side Validations.

2. Server Side Scripting with Database Connectivity  : 15 hrs

PHP(8 Hrs.): Introduction to Server Side Scripting Language, PHP introduction. Basic PHP Syntax, Comments in PHP, Variables, PHP Operators, Control Structures(If else, switch, all loops), Arrays, For Each Loop, Functions, Form Handling, PHP $_GET, PHP $_POST, PHP $_REQUEST, PHP date (} Function, PHP include File, File Handling, File Uploading, PHP Sessions, Sending Emails, PHP Cookies.

MySQL(7 Hrs.): Introduction to MySQL, PHP MySQL Connect to a Database, Closing a Connection, MySQL Data Types, MySQL Insert, MySQL Select, MySQL Where Clause, MySQL Delete, MySQL Update, MySQL Aggregate Functions(sum, avg, count etc); MySQL Order by and Group by Clause, MySQL Subqueries, MySQL Joins,

3. Advanced Server Side Scripting  : 15 hrs

Object Oriented Programmtng in PHP:  Classes and Objects, Defining and Using properties and methods, Constructors and Destructors, Method Overriding, Encapsulation, Inheritance, Polymorphism, Static Members,  Exception Handling  

AJAX(Asynchronons JavaSeript and XML): Using PHP, Using PHP +MySQL

jQuery: Playing With Elements, Hiding and Unhiding Images. Jquery UI 

JOOMLA: Introduction To CMS, Installation, Handling Joomla Back End.. Customization In Joomla, Introduction To Extensions, Installation and Uses Of Extensions in Joomla, Template Development In Joomla, Artiseer(IDE), Module Development In Joomla, Component Development In Joomla, Introduction To MVC(Model, View and Controller)

WordPress Administrator Level: Theme Integration, Creating pages, Managing Posts, Managing Widgets

Laboratory Works

Laboratory works should be done covering all the topics listed above and a small project work should be carried out using the concept learnt in this course. Project should be assigned on Individual Basis.

 Text and Reference Books

Text Books

  1. Harvey M. Deitel, Paul J. Deitel & Abbey Deitel, “Internet and World Wide Web: How to Program”, 5th Edition, Pearson Education, 2012, ISBN: 9780273764021
  2. Robin Nixon, “Learning PHP, MySQL, JavaScript and CSS”,2 nd Edition, 0′ Reilly Media, 2012, ISBN 978-44.9319267

Reference Books 

  1. Da Flanagan. JavaScript; The Definitive Guide”, O’ Reilly Media, 2011. ISBN. 139780596505524
  2. David Sawyer McFarland“JavaScript & jQuery; The Missing Manual” 2nd Edition, Pogue Press, 2011, ISBN: 978-1449399023
  3. Luke Welling & Laura Thomson, “PHP and MySQL Web Development”, 5th Edition, Developer’s Library, 2014, ISBN: 978-0321833891

Past Questions Year (2019) Click

Group B

Attempt any Six question

2. Explain the concept, structure and importance of Document Object Model (DOM).

3. What is JavaScript? Write a JavaScript to print largest & smallest among 10 elements of an array

4. What is dialog box? Explain different dialog boxes with suitable example in JavaScript.

5. Explain two HTTP functions to accept the user values from interface with suitable PHP program.

6. What is the use of JQuery? Write the sample program to show and hide the certain with use of JQuery.

7. Why Ajax is required in web development? Write an sample program to synchronize data between JavaScript and PHP.

8. Why is CMS? Write the steps to create a sub-menu in WordPress or Joomla.

Group C

Attempt any Two question

9. Design the following form in HTML and display the value in the result box after calculating basic arithmetic operations based on user input with use of JavaScript

10. Write an Object-Oriented PHP Program to implement the concept of inheritance in considering with following class diagram with use of constructor for 20 students.

11. Design following form in HTML and write corresponding PHP and SQL code to store the user's values after satisfying following validation rules.

a) Length of full name up to 40 characters.
b) Email address must be valid email address.
c} Username must be start with string followed by number.
d) Password length must be more than eight characters.
Assume your own database and database connectivity constrains if necessary.

Past Questions Year (2019) Solutions Click

Group B

2. Explain the Concept, Structure, and Importance of Document Object Model (DOM)

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can manipulate the structure, style, and content of web pages. The DOM allows languages such as JavaScript to access and update the content, structure, and style of a web page dynamically.

Concept:

The DOM represents the structure of the HTML or XML document as a tree of nodes. Each node represents a part of the document (element, text, attribute, etc.). JavaScript can interact with these nodes to modify the page's content.

Structure:

  • Document: The root node of the DOM tree.
  • Element Nodes: Correspond to HTML elements (like <div>, <p>, etc.).
  • Text Nodes: Represent text within elements.
  • Attribute Nodes: Represent the attributes of HTML elements (e.g., id, class).
  • Comment Nodes: Represent comments in the HTML or XML document.

Here’s an example of how an HTML document might be represented in the DOM:

<html>
  <body>
    <div id="content">
      <h1>Hello, World!</h1>
    </div>
  </body>
</html>

In the DOM, it would look like this:

Document
    └── html
        └── body
            └── div (id="content")
                └── h1 (Hello, World!)

Importance:

  • Dynamic Interaction: It allows developers to update the content, structure, and styles of a webpage in response to user actions.
  • Cross-Language Compatibility: The DOM is language-agnostic, allowing manipulation through JavaScript, Python, and other languages.
  • Enhanced User Experience: With DOM, developers can build interactive, real-time applications by updating parts of the webpage without reloading the entire page (using AJAX, for instance).

3. What is JavaScript? Write a JavaScript to Print Largest & Smallest Among 10 Elements of an Array

JavaScript is a lightweight, interpreted programming language primarily used for web development. It enables interactive web pages by manipulating the DOM and responding to user events.

Here’s a JavaScript program to find the largest and smallest elements in an array of 10 elements:

// JavaScript program to find the largest and smallest numbers in an array

let arr = [5, 8, 12, 45, 23, 89, 34, 67, 2, 90];

// Initializing variables to store largest and smallest values
let largest = arr[0];
let smallest = arr[0];

// Looping through the array to compare each element
for (let i = 1; i < arr.length; i++) {
    if (arr[i] > largest) {
        largest = arr[i];
    }
    if (arr[i] < smallest) {
        smallest = arr[i];
    }
}

// Printing the largest and smallest numbers
console.log("Largest number: " + largest);
console.log("Smallest number: " + smallest);

Output:

Largest number: 90
Smallest number: 2

4. What is a Dialog Box? Explain Different Dialog Boxes with a Suitable Example in JavaScript.

A Dialog Box is a small pop-up window that displays messages or asks for input from the user in web applications. JavaScript provides built-in dialog boxes to interact with users.

There are three types of dialog boxes in JavaScript:

  1. Alert Box: Displays a message to the user.

    alert("This is an alert box!");
    
  2. Confirm Box: Asks the user to confirm or cancel a decision.

    var result = confirm("Do you want to proceed?");
    if (result) {
        console.log("User clicked OK");
    } else {
        console.log("User clicked Cancel");
    }
    
  3. Prompt Box: Allows the user to input some data.

    var name = prompt("Enter your name:");
    console.log("Hello, " + name);
    

Examples:

<!DOCTYPE html>
<html>
<body>

<button onclick="showAlert()">Alert Box</button>
<button onclick="showConfirm()">Confirm Box</button>
<button onclick="showPrompt()">Prompt Box</button>

<script>
function showAlert() {
  alert("This is an alert box!");
}

function showConfirm() {
  var result = confirm("Do you want to proceed?");
  if (result) {
    alert("User clicked OK");
  } else {
    alert("User clicked Cancel");
  }
}

function showPrompt() {
  var name = prompt("Enter your name:");
  alert("Hello, " + name);
}
</script>

</body>
</html>

5. Explain Two HTTP Functions to Accept User Values from Interface with a Suitable PHP Program

In PHP, two common HTTP methods for accepting user input from forms are $_GET and $_POST.

  • $_GET: Retrieves data sent by a URL query string.
  • $_POST: Retrieves data sent by the form submission (method POST).
Example using $_GET:
<!-- HTML Form -->
<form method="GET" action="process_get.php">
    Name: <input type="text" name="name">
    <input type="submit" value="Submit">
</form>

<!-- PHP Script (process_get.php) -->
<?php
if (isset($_GET['name'])) {
    $name = $_GET['name'];
    echo "Hello, " . htmlspecialchars($name);
}
?>
Example using $_POST:
<!-- HTML Form -->
<form method="POST" action="process_post.php">
    Name: <input type="text" name="name">
    <input type="submit" value="Submit">
</form>

<!-- PHP Script (process_post.php) -->
<?php
if (isset($_POST['name'])) {
    $name = $_POST['name'];
    echo "Hello, " . htmlspecialchars($name);
}
?>

6. What is the Use of JQuery? Write the Sample Program to Show and Hide Certain Elements Using JQuery

jQuery is a fast, small, and feature-rich JavaScript library that simplifies HTML document traversal, event handling, and animations.

Use of jQuery:

  • Simplifies DOM Manipulation: jQuery provides an easy way to interact with HTML elements.
  • Cross-browser Compatibility: It abstracts the differences between browsers, making it easier to work with them.
  • Animations: Provides built-in methods for creating animations like showing/hiding elements.
Example: Show and Hide Elements Using jQuery
<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<button id="showButton">Show Element</button>
<button id="hideButton">Hide Element</button>

<div id="myElement" style="display:none;">This is a hidden element</div>

<script>
    $(document).ready(function(){
        $("#showButton").click(function(){
            $("#myElement").show();  // Show the element
        });

        $("#hideButton").click(function(){
            $("#myElement").hide();  // Hide the element
        });
    });
</script>

</body>
</html>

7. Why is Ajax Required in Web Development? Write a Sample Program to Synchronize Data Between JavaScript and PHP

Ajax (Asynchronous JavaScript and XML) is required in web development to allow web pages to communicate with the server without reloading the page. This results in a more interactive and dynamic user experience.

Why Ajax is Important:

  • Improves User Experience: Web pages can load new data or interact with the server without refreshing.
  • Faster Load Times: Only specific portions of a webpage are updated, reducing the need to reload the entire page.
  • Dynamic Interactions: Data can be sent and received asynchronously, enabling real-time interactions.
Example: Synchronize Data Between JavaScript and PHP using Ajax
<!-- HTML -->
<button onclick="loadData()">Get Data</button>
<div id="result"></div>

<script>
function loadData() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "process_ajax.php", true);
    xhr.onload = function() {
        if (xhr.status == 200) {
            document.getElementById("result").innerHTML = xhr.responseText;
        }
    };
    xhr.send();
}
</script>

<!-- PHP (process_ajax.php) -->
<?php
echo "Hello, this is data from PHP!";
?>

8. What is CMS? Write the Steps to Create a Sub-menu in WordPress or Joomla

CMS (Content Management System) is software that allows users to create, manage, and modify digital content on a website without needing specialized technical knowledge.

Steps to Create a Sub-menu in WordPress:
  1. Log in to the WordPress Admin Panel.
  2. Go to Appearance > Menus.
  3. Create a new menu or edit an existing one.
  4. Add Menu Items:
    • From the left sidebar, add pages, categories, or custom links.
    • To create a sub-menu, drag a menu item slightly to the right beneath the parent item.
  5. Save the Menu.
Steps to Create a Sub

-menu in Joomla:

  1. Log in to the Joomla Admin Panel.
  2. Go to Menus > Manage.
  3. Create a New Menu Item or Edit an existing menu.
  4. Choose Parent Item: When adding a new item, specify the parent item under which the new item will appear.
  5. Save Changes.

Group C

9. Design the Following Form in HTML and Display the Value in the Result Box After Calculating Basic Arithmetic Operations Based on User Input Using JavaScript

<!DOCTYPE html>
<html>
<body>

<h2>Basic Arithmetic Operations</h2>

<form name="calculator">
  First Number: <input type="number" name="num1"><br><br>
  Second Number: <input type="number" name="num2"><br><br>
  <input type="button" value="Add" onclick="calculate('add')">
  <input type="button" value="Subtract" onclick="calculate('subtract')">
  <input type="button" value="Multiply" onclick="calculate('multiply')">
  <input type="button" value="Divide" onclick="calculate('divide')"><br><br>
</form>

<h3>Result:</h3>
<p id="result"></p>

<script>
function calculate(operation) {
  var num1 = parseFloat(document.calculator.num1.value);
  var num2 = parseFloat(document.calculator.num2.value);
  var result;
  
  if (operation === 'add') {
    result = num1 + num2;
  } else if (operation === 'subtract') {
    result = num1 - num2;
  } else if (operation === 'multiply') {
    result = num1 * num2;
  } else if (operation === 'divide') {
    result = num1 / num2;
  }
  
  document.getElementById("result").innerHTML = "Result: " + result;
}
</script>

</body>
</html>

10. Write an Object-Oriented PHP Program to Implement the Concept of Inheritance Considering the Following Class Diagram with Use of Constructor for 20 Students

// Parent Class: Person
class Person {
    public $name;
    public $age;
    
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
    
    public function display() {
        echo "Name: " . $this->name . ", Age: " . $this->age . "<br>";
    }
}

// Child Class: Student
class Student extends Person {
    public $student_id;
    
    public function __construct($name, $age, $student_id) {
        parent::__construct($name, $age);  // Calling parent constructor
        $this->student_id = $student_id;
    }
    
    public function displayStudentInfo() {
        $this->display();
        echo "Student ID: " . $this->student_id . "<br>";
    }
}

// Create an array of 20 Student objects
$students = [];
for ($i = 1; $i <= 20; $i++) {
    $students[] = new Student("Student " . $i, 18 + $i, "S" . $i);
}

// Display information for all students
foreach ($students as $student) {
    $student->displayStudentInfo();
}

11. Design Following Form in HTML and Write Corresponding PHP and SQL Code to Store User's Values After Satisfying Validation Rules

<!-- HTML Form -->
<form method="POST" action="process_form.php">
    Full Name: <input type="text" name="fullname" maxlength="40" required><br>
    Email: <input type="email" name="email" required><br>
    Username: <input type="text" name="username" pattern="[A-Za-z]+[0-9]+" required><br>
    Password: <input type="password" name="password" minlength="8" required><br>
    <input type="submit" value="Submit">
</form>
// PHP (process_form.php)
<?php
// Database Connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $fullname = $_POST['fullname'];
    $email = $_POST['email'];
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    
    // Validation
    if (strlen($fullname) > 40) {
        echo "Full name is too long.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email address.";
    } elseif (!preg_match("/^[A-Za-z]+[0-9]+$/", $username)) {
        echo "Username must start with letters followed by numbers.";
    } elseif (strlen($password) < 8) {
        echo "Password must be at least 8 characters long.";
    } else {
        // SQL query to insert user data
        $sql = "INSERT INTO users (fullname, email, username, password) VALUES ('$fullname', '$email', '$username', '$password')";
        
        if ($conn->query($sql) === TRUE) {
            echo "User registered successfully.";
        } else {
            echo "Error: " . $conn->error;
        }
    }
}

$conn->close();
?>

This covers each question from Group B and C.

No comments:

Post a Comment

Popular Posts