MC5303 Web Programming Essentials
MC5303 Web Programming Essentials
UNIT V PHP 9
Introduction - How web works - Setting up the environment (LAMP server) - Programming basics
Print/echo - Variables and constants – Strings and Arrays – Operators, Control structures and looping
structures – Functions – Reading Data in Web Pages - Embedding PHP within HTML - Establishing
connectivity with MySQL database.
TOTAL : 45 PERIODS
REFERENCES:
1. David Flanagan, “JavaScript: The Definitive Guide, Sixth Edition”, O'Reilly Media, 2011
2. Harvey & Paul Deitel& Associates, Harvey Deitel and Abbey Deitel, “Internet and World Wide Web -
How To Program”, Fifth Edition, Pearson Education, 2011
3. James Lee, BrentWare , “Open Source Development with LAMP: Using Linux, Apache, MySQL, Perl,
and PHP” AddisonWesley, Pearson 2009
4. Thomas A. Powell, “HTML & CSS: The Complete Reference”, Fifth Edition, 2010
5. Thomas A Powell, Fritz Schneider, “JavaScript: The Complete Reference”, Third Edition, Tata McGraw
Hill, 2013
6. Thomas A Powell, “Ajax: The Complete Reference”, McGraw Hill, 2008
Formatting Tags
more such items in the same or different electronic document. Upon clicking the mouse
button on a hyper-linked item, the reader is automatically transferred to the other end of
the hyperlink which could be another document or another website. Also called hotlink.
28) How will you embed the external style sheet? (May 2014)
In external style sheet is ideal when the style is applied to many pages. With an external
style sheet, you can change the look of an entire Web site by changing just one file.Each
page must include a link to the style sheet with the <link> tag. The <link> tag goes inside
the head section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
An external style sheet can be written in any text editor. The file should not contain any html tags.
The style sheet file must be saved with a .css extension. An example of a style sheet file is shown
below:
"myStyle.css":
body {
background-color: lightblue;}
h1 {
color: navy;
margin-left: 20px;}
29)Differentiate between client-side scripting and server side scripting.(MAY 2015)
Server side scripting is used to create dynamic pages based a number of conditions when the
users browser makes a request to the server.Client side scripting is used when the users browser
already has all the code and the page is altered on the basis of the users input.Client side scripting
is that which runs on user browser. client side scripting is used for validation JavaScript, VB script
web pages you may be presented with an image which fills the screen. On that picture there may
hotspots which, when clicked, will take you to another page. A typical example of this would be a
site map of an organization or a map of the world.
UNIT- III
1) What is JavaScript?
JavaScript is a platform-independent, event-driven, interpreted client-side scripting language
developed by Netscape Communications Corp. and Sun Microsystems.
2) What are the uses of JavaScript?
JavaScript can be used as an alternate to java applets, Javascript can be get embedded in
XHTML, javascript can be used to create cookies
3) What are the Basic Terminology of Programming Languages?
Expression, Statement, Keyword, Reserved Word.
4) What is meant by statements in Javascript?
Statements are the essence of a language like JavaScript. They are instructions to the interpreter to
carry out specific actions. For example, one of the most common statements is an assignment.
Assignment uses the = operator and places the value on the right-hand side into the variable on the
left. For example, x = y + 10; adds 10 to y and places the value in x.
HTML is used for simple web page design, HTML with FORM is used for both form design
and Reading input values from user, Scripting Language is used for Validating the given input
values weather it is correct or not, if the input value is incorrect, the user can pass an error
message to the user, Using form concept various controls like Text box, Radio Button,
Command Button, Text Area control and List box can be created.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;}}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();"
method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
29)How to write function using Java Script? Give Example. (May 2014)
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1,
parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
functionName(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments are used as local variables
UNIT-IV
Cookies can be disabled on user browsers , Cookies are transmitted for each HTTP
request/response causing overhead on bandwidth, No security for sensitive data
9) What does Rollover mean?
Rollover is a JavaScript technique used by Web developers to produce an effect in which the
appearance of a graphical image changes when the user rolls the mouse pointer over it.
Rollover also refers to a button on a Web page that allows interactivity between the user and
the Web page. It causes the button to react by either replacing the source image at the button
with another image or redirecting it to a different Web page.
10) What is meant by animating the canvas?
Animation involves repeatedly clearing the canvas and drawing an image on it. To create
smooth animations, you need to minimize the time between clearing the canvas and
completing the new drawing, and you need to keep the changes relatively small from image to
image.
For smooth animation, use the following sequence:
1. Model—calculate small changes in image substitution, position, rotation, color, or scale.
2. Clear—Clear part or all of the canvas.
3. Draw—Draw any images, using the pre-calculated values. Stroke or fill any paths, shapes,
or strings., Repeat steps 1-3.
11) Define Compositing
In video terminology, compositing is the merging of two video tracks in order to produce a
new single frame the combined tracks. The term may also be used to describe the overlaying
of text and titles on video clips.
We can pass parameters to the server using either the GET or POST method. The following
code snippets show the example of both the methods:
Get: XmlHttpObject.Open("GET","file1.txt", true);
Post: XmlHttpObject.Open("POST", "file2.txt", true);
27) What are the extender controls?
The extender controls uses a block of JavaScript code to add new and enhanced capabilities to
ASP.NET. The developers can use a set of sample extender controls through a separate
download - AJAX Control Toolkit (ACT).
28) List out the advantages and limitations of AJAX. (May 2014)
Advantages: Better interactivity, Easier navigation, Compact, Backed by reputed brands
Disadvantages: It is difficult to bookmark a particular state of the application, Function
provided in the code-behind file do not work because the dynamic pages cannot register
themselves on browsers history engine automatically.
29)Define the super classes and subclasses with example.(MAY 2015)
Every class can have a super class from which it inherits properties and methods. Any class
can be extended, or sub-classed so the resulting subclass can inherit its parent's behavior. As
we have seen, JavaScript supports prototype inheritance instead of class based. It's possible for
inheritance to happen other ways, however.
<script language="javascript" type="text/javascript">
function superClass()
{
this.supertest = superTest; //attach method superTest
}
function subClass()
{
this.inheritFrom = superClass;
this.inheritFrom();
this.subtest = subTest; //attach method subTest
}
function superTest()
{
return "superTest";
}
function subTest()
{
return "subTest";
}
var newClass = new subClass();
alert(newClass.subtest()); // yields "subTest"
alert(newClass.supertest()); // yields "superTest"
</script>
30) What is the use of Constructor?(MAY 2016)
JavaScript constructors are special methods that create and initialize the properties for newly
created objects. A constructor must be able to reference the object on which it is to operate.
UNIT-V
1) What is PHP?
PHP is a powerful tool for making dynamic and interactive Web pages, PHP stands for
Hypertext Preprocessor, PHP is a server-side scripting language, like ASP, PHP scripts are
executed on the server, PHP supports many databases (MySQl, ORACLE), and PHP is open
source software.
2) How PHP works for the web?
Understanding how the World Wide Web works is necessary to understand how PHP
13) What are the three different types of control structures in PHP?
Control Structures are the structures within a language that allow us to control the flow of
execution through a program or script, Grouped into conditional (branching) structures
(e.g. if/else) and repetition structures (e.g. while loops) and For loops.
14) Give one Example for If/Else statement.
Example if/else if/else statement:
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5))
{
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;}
15) Write the syntax for Switch –Case Structures.
Switch ($number)
{
Case 1:
echo “small”;
break;
Case 2:
echo “medium”;
break;
Case 3:
echo “large”;
break;
Default:
echo “That is not a valid code.”;
}
PART B
UNIT I
1) Explain in detail the basic internet protocols.
It is a standard protocol for communication between web browsers and web servers .It is a text
oriented protocol.
Steps:
HTTP protocol defines four steps for each request from a client to the server. They are
Operation Description
Options Request information about available options.
GET Get the document identified in URL
HEAD Get meta information about document identified in
URL
POST Gives information to the server.
PUT Stores the document in specified URL
DELETE Deletes the specified URL.
TRACE It loopbacks request message
Connect It is used by proxies
Response.
.closing the connection
Making the Connection:
The client establishes a TCP connection to the server. By default, the connection is made on port
80. Other ports may be specified in the URL.
Making a Request:
The client sends a message to the server requesting a page at the specified URL. There are 8 types
of HTTP request. They are
Operation Description
OptionsRequest information about available options.
GET Get the document identified in URL
HEAD Get meta information about document identified in URL
POST Gives information to the server.
PUT Stores the document in specified URL
DELETE Deletes the specified URL.
TRACE It loopbacks request message
Connect It is used by proxies
The Response
The server sends a response to the client often the reponse begins with a response code, followed
by MIME header information, blank line, then requested information or an error message
SMTP
SMTP stands for Simple Mail Transfer Protocol. It is simple ASCII protocol. This protocol
establishes the TCP connection to port 25, act as client, waits for the receiving machine operating
as the server to talk first.
The server starts by sending a line of text giving its identify and telling whether it is prepared to
revive mail. If it is not, the client releases the connection and tries again later.
If the server is willing to accept email, the client announces whom the email is coming from and
whom the message is returned to.
If such a recipient exist the server gives the client the go ahead to send the message and the server
acknowledge it. No checksum are needed because TCP provides a reliable byte stream.
When all the email has been exchanged in both directions the connections is released.
Example dialog for sending the message including the numerical codes used by SMTP.
S: Server
C:Client-
S:220xyz.com SMTP service ready
C:HELO abod.com
S:250 xyz.com says hello to abed.com
C:MAIL FROM:[email protected]
S:250 sender ok
C:RCPT TO:[email protected]
S:250 recipient ok
C:DATA
S:354 send mail; end with “,”On a line by itself
C: from:[email protected]
C:To [email protected]
C:MIME_version:1.0
C: Messages_id:[email protected]
C:Content_Type:Multiport/alternative
C:Subject:Hi Son
C:Content_Type:text/enriched
C:Happy birthday to you Joseph
C: Content_type:audio/basic
C:Content_transfer_encoding:base64
C:
S:250 message accepted
C:QUIT
S:221 xyz.com closing connection
The commands used are
1.Hello- to Establish Connection.
2.RCPT- to send a single message to multiple receivers.
3. MAIL_FROM- to introduce the sender to the receiver.
4. DATA- The message to be sent in e-mail which will end with.
5. HELP-to know what command the SMTP server will again.
Advantages:
Well Defined.
Simple to use
Disadvantages:
Messages should not exceed 64KB length.
Infinite mail can be triggered.
If the client and server have different timeout, one of them may give up while the other is till busy
unexpectedly terminating the connection.
POP3:
St. Joseph’s College of Engineering MCA 19
MC5303 Web Programming Essentials 2018-19
POP3 stands for Post Office Protocol Version3.
POP3 allows user Transfer Agent to contract message transfer agent and allow e-mail to be copied
from ISP to the user.
Two situations can be handled by POP3
If both the sender and reciver are online.
If sender is online but reciver is not.
GUI
Control Process
Control Process
Data Transfer Process
Data Transfer Process
Data Transfer Connection
Steps:
1. POP3 begins when user starts mail reader.
2. Mail reader calls up the ISP and establishes a TCP Connection with MTA at port110
3.POP3 goes through 3 states in sequence after connection establishment
Authorization:
It deals with having user login.
Transaction:
It deals with the user collecting the e-mails and marking them for deletion from the mailbox.
Update:
Actually causes email to be deleted.
Commands:
USER – Gets the user name
PASS- Gets the password of the user.
LIST- Causes the server to list the contents of mailbox, one message per line, giving the length of
the message period (.) terminates the list.
RETR- Used to retrieve the messages
DELE- Used to mark the messages to be deleted.
QUIT- Used to terminate the transaction state and enter update state.
FTP:
The File transfer protocol sets the rules for transferring files between computers. When user wants
to download a file from the server FTP is used. There are various issues that must be solved
during such file transfer. These issues can be described as follows
Client must have an authority to download particular file.
The hardware and software on both the computers might be different.
The data interpretation and data formats on client and server might be different.
FTP provides the mechanism to handle these issues internally and user remains free different.
FTP uses two connections between client and server. One connection is used for actual data
transfer and other is used for control information. This separation of data and commands makes
the FTP more Efficient.
When client makes a request for particular file download then using the data transfer connection
actual data gets transmitted form server to the client. AT the same time server keeps track of how
much data is sent so far and how much is remaining. This tracking can be done using the control
transfer connection. Hence during the file downloading/uploading we can see a message about
how many bytes are getting transferred and how much time is remaining .Various commands used
in FTP are
TCP
It is a higher-level protocol extends IP to provide additional functionality
Reliable communication based on the concept of communication
TCP adds concept of a connection on top of IP
Provides guarantee that packets delivered
Provide two-way (full duplex) communication
A and B both send messages to one another at the same time.
Reliable data transmission by demanding an ACK for each packet it sends via IP
Splitting longer messages into shorter ones
Reassembling on receiver side.
TCP also adds concept of a port
The port concept allows TCP to communicate with many different applications on a machine.
TCP header contains port number representing an application program on the destination computer
Some port numbers have standard meanings
Example: port 25 is normally used for email transmitted using the Simple Mail Transfer Protocol
(SMTP)
Other port numbers are available first-come-first served to any application
Assigned by IANA
0-1023 requested only by the applications that are run by the system at boot-up
1024-65535 used by the first application on a system
Exchange electronic mail (e-mail) to any Internet user in any location on the planet.
The concept of sending electronic text messages between parties in a way analogous to mailing
letters or memos predates the creation of the Internet. Even today it can be important to distinguish
between Internet and internal e-mail systems. Internet e-mail may travel and be stored unencrypted
on many other networks and machines out of both the sender's and the recipient's control. During
this time it is quite possible for the content to be read and even tampered with by third parties, if
anyone considers it important enough. Purely internal or intranet mail systems, where the
St. Joseph’s College of Engineering MCA 24
MC5303 Web Programming Essentials 2018-19
information never leaves the corporate or organization's network, are much more secure, although
in any organization there will be IT and other personnel whose job may involve monitoring, and
occasionally accessing, the e-mail of other employees not addressed to them.
5)Write short notes on Domain Name System.
Domain Name System
The name of each host computer consists of a series of words separated by dots. The last part of
the domain name is called the top-level domain (TLD).
The last two parts of a host computer name constitute the domain.
The second to last part of the name (second-level-domain) is chosen by the organization that owns
the computer. Eg:yahoo.com
Because most organizations own more than on computer on the internet, most host computer
names have at least one more part, preceding the domain name called third-level-domain. Eg:
www.yahoo.com, mail.yahoo.com.
A domain name system (DNS) server translates between the numeric IP addresses that identify
each host computer on the internet and the corresponding domain names.
The DNS domain namespace, as shown in the following figure, is based on the concept of a tree of
named domains. Each level of the tree can represent either a branch or a leaf of the tree. A branch
is a level where more than one name is used to identify a collection of named resources. A leaf
represents a single name used once at that level to indicate a specific resource.
DNS Domain Name Hierarchy
Types of DNS Domain Names
Name
Description Example
Type
This is the top of the tree, representing an unnamed level; it A single period (.) or a period used at
Root is sometimes shown as two empty quotation marks (""), the end of a name, such as
St. Joseph’s College of Engineering MCA 25
MC5303 Web Programming Essentials 2018-19
Domain
indicating a null value. “example.microsoft.com.”
Host or Names that represent a leaf in the DNS tree of names and ““host-a.example.microsoft.com.”,
Resource Identify a specific resource. Typically, the leftmost label of where the first label (“host-a”) is the
name a DNS domain name identifies a specific computer on the DNS host name for a specific
network. For example, if a name at this level is used in a computer on the network.
host (A) RR, it is used to look up the IP address of
computer based on its host name.
The Internet Domain Name System is managed by a Name Registration Authority on the Internet,
responsible for maintaining top-level domains that are assigned by organization and by
country/region. These domain names follow the International Standard 3166. Some of the many
existing abbreviations, reserved for use by organizations, as well as two-letter and three-letter
abbreviations used for countries/regions are shown in the following table:
S.N
Method and Description
.
GET
1 The GET method is used to retrieve information from the given server using a given URI.
Requests using GET should only retrieve data and should have no other effect on the data.
HEAD
2
Same as GET, but only transfer the status line and header section.
POST
3 A POST request is used to send data to the server, for example customer information, file
upload etc using HTML forms.
PUT
4
Replace all current representations of the target resource with the uploaded content.
DELETE
5
Remove all current representations of the target resource given by URI.
CONNECT
6
Establish a tunnel to the server identified by a given URI.
OPTIONS
7
Describe the communication options for the target resource.
TRACE
8
Perform a message loop-back test along the path to the target resource.
Using client-side scripting to change interface behaviors within a specific web page, in response to
mouse or keyboard actions or at specified timing events. In this case the dynamic behavior occurs
within the presentation. Such web pages use presentation technology called rich interfaced pages.
Client-side scripting languages like JavaScript or ActionScript, used for Dynamic HTML
(DHTML) and Flash technologies respectively, are frequently used to orchestrate media types
(sound, animations, changing text, etc.) of the presentation. The scripting also allows use of remote
scripting, a technique by which the DHTML page requests additional information from a server,
using a hidden Frame, XMLHttpRequests, or a Web service The Client-side content is generated
on the user's computer.
The web browser retrieves a page from the server, then processes the code embedded in the page
(often written in JavaScript) and displays the retrieved page's content to the user. The innerHTML
property (or write command) can illustrate the client-side dynamic page generation: two distinct
pages, A and B, can be regenerated as document. innerHTML = A anddocument. innerHTML = B;
or "on load dynamic" by document.write(A) and document.write(B).
Server-side scripting and content creation
Using server-side scripting to change the supplied page source between pages, adjusting the
sequence or reload of the web pages or web content supplied to the browser. Server responses may
be determined by such conditions as data in a posted HTML form, parameters in the URL, the type
of browser being used, the passage of time, or a database or server state. Such web pages are often
created with the help of serverside languages such as PHP, Perl, ASP, ASP.NET, JSP, ColdFusion
and other languages. These server-side languages typically use the Common Gateway Interface
(CGI) to produce dynamic web pages. These kinds of pages can also use,
on the client-side, the first kind (DHTML, etc.).
Server-side dynamic content is more complicated:
(1) The client sends the server the request.
(2) The server receives the request and processes the server-side script such as [PHP] based on the
query string, HTTP POST data, cookies, etc.
The dynamic page generation was made possible by the Common Gateway Interface, stable in
1993. Then Server Side Includes pointed a more direct way to deal with server-side scripts,
at the web servers.
Combining client and server side
Ajax is a web development technique for dynamically interchanging content with the server-side,
without reloading the web page. Google Maps is an example of a web application that uses Ajax
techniques and database.
Application areas of Dynamic Website
Dynamic web page is required when following necessities arise:
• Need to change main pages more frequently to encourage clients to return to site.
• Long list of products / services offered that are also subject to up gradation
• Introducing sales promotion schemes from time to time
• Need for more sophisticated ordering system with a wide variety of functions
• Tracking and offering personalized services to clients.
• Facility to connect Web site to the existing back-end system
The fundamental difference between a static Website and a dynamic Website is a static website is
no more than an information sheet spelling out the products and services while a dynamic
website has wider functions like engaging and gradually leading the client to online ordering.
But both static web site design and dynamic websites design can be designed for search engine
optimization. If the purpose is only to furnish information, then a static website should suffice.
Dynamic website is absolutely necessary for e-commerce and online ordering
Advantages:
Enhances functionality of a website, Simple and Easy to update, New content is responsible for
bringing traffic to the site that helps in the search engines optimization, Acts as a system to permit
staff or users to collaborate
Disadvantages:
Expensive to develop, as web solutions developers use their expertise and knowledge to develop
such websites, Hosting costs a little more, again the involvement of experts
When client makes a request for particular file download then using the data transfer connection
actual data gets transmitted form server to the client. AT the same time server keeps track of how
much dat is sent so far and how much is remaining. This tracking can be done using the control
transfer connection. Hence during the file downloading/uploading we can see a message about
how many bytes are getting transferred and how much time is remaining .Various commands used
in FTP are
Web Browser
The primary purpose is to bring information resources to the user.
An application for retrieving, presenting, and traversing information resources.
Web Server
The term web server or webserver can mean one of two things:
A computer program that accepts HTTP requests and return HTTP responses with optional data content.
A computer that runs a computer program as described above.
HyperText Markup Language
It is a standard protocol for communication between web browsers and web servers .It is a text oriented
protocol.
Steps:
HTTP protocol defines four steps for each request from a client to the server. They are
Making a Request:
ii) What is POP3 and What are the advantages and limitations of POP3?
POP3:
POP3 stands for Post Office Protocol Version3.
POP3 allows user Transfer Agent to contract message transfer agent and allow e-mail to be copied from
ISP to the user.
Two situations can be handled by POP3
If both the sender and reciver are online.
If sender is online but reciver is not.
Steps:
1. POP3 begins when user starts mail reader.
2. Mail reader calls up the ISP and establishes a TCP Connection with MTA at port110
3.POP3 goes through 3 states in sequence after connection establishment
Authorization:
It deals with having user login.
Transaction:
It deals with the user collecting the e-mails and marking them for deletion from the mailbox.
Update:
UNIT II
1) Discuss the various features available in HTML to format the text with example.
Html formatting, Fonts
HTML Text Formatting Tags
Tag Description
<b> Defines bold text
<em> Defines emphasized text
<small> Defines smaller text
<strong> Defines important text
<sub> Defines subscripted text
<sup> Defines superscripted text
<b>
<!DOCTYPE html>
<html>
<body>
<p>This is normal text - <b>and this is bold text</b>.</p>
</body>
</html>
This is normal text - and this is bold text
<em>
<!DOCTYPE html>
<html>
<body>
<em>Emphasized text</em><br>
<strong>Strong text</strong><br>
<dfn>Definition term</dfn><br>
<code>A piece of computer code</code><br>
<samp>Sample output from a computer program</samp><br>
St. Joseph’s College of Engineering MCA 33
MC5303 Web Programming Essentials 2018-19
<kbd>Keyboard input</kbd><br>
<var>Variable</var>
</body>
</html>
Emphasized text
Strong text
Definition term
A piece of computer code
Sample output from a computer program
Keyboard input
Variable
Subscript and superscript
<!DOCTYPE html>
<html>
<body>
<p>This text contains <sub>subscript</sub> text.</p>
<p>This text contains <sup>superscript</sup> text.</p>
</body>
</html>
This text contains subscript text.
This text contains superscript text.
Fonts
<!DOCTYPE html>
<html>
<body>
<p><font size="3" color="red">This is some text!</font></p>
<p><font size="2" color="blue">This is some text!</font></p>
<p><font face="verdana" color="green">This is some text!</font></p>
<p><strong>Note:</strong> The font element was deprecated in HTML 4.01, and is not supported in
HTML5.</p>
</body>
</html>
This is some text!
This is some text!
This is some text!
4) Explain how tables can be inserted into HTML document with example.
HTML Tables
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is
divided into data cells (with the <td> tag). td stands for "table data," and holds the content of a data cell. A
<td> tag can contain text, links, images, lists, forms, other tables, etc.
Table Example
<table border="1">
<tr> <td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr> <td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Row1 cell1 Row1 cell2
Row 2 cell2 Row2 cell 2
HTML Tables and the Border Attribute
If you do not specify a border attribute, the table will be displayed without borders. Sometimes this can be
useful, but most of the time, we want the borders to show. To display a table with borders, specify the
border attribute:
<table border="1">
<tr> <td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
HTML Table Headers
Header information in a table are defined with the <th> tag. All major browsers will display the text in the
<th> element as bold and centered.
<table border="1">
<tr> <th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
5) What is the significance of using forms on the web page? Enlist various components
used on form.(May 2015)
Form is a typical layout on the web page by which a user can interact with can interact with the web page.
Typical component of forms are
HTML Forms
HTML forms are used to pass data to a server.
An HTML form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and
more. A form can also contain select lists, textarea, fieldset, legend, and label elements.
The <form> tag is used to create an HTML form:
<form>
.
input elements
.
</form>
HTML Forms - The Input Element
The most important form element is the <input> element.
The <input> element is used to select user information.
An <input> element can vary in many ways, depending on the type attribute. An <input> element can be of
type text field, checkbox, password, radio button, submit button, and more.
The most common input types are described below.
Text Fields
<input type="text"> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
How the HTML code above looks in a browser:
Top of Form
First name:
Last name:
Bottom of Form
Note: The form itself is not visible. Also note that the default width of a text field is 20 characters.
Password Field
<input type="password"> defines a password field:
<form>
Password: <input type="password" name="pwd">
</form>
How the HTML code above looks in a browser:
Top of Form
Password:
Bottom of Form
Note: The characters in a password field are masked (shown as asterisks or circles).
Radio Buttons
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a limited
number of choices:
<form>
<input type="radio" name="sex" value="male">Male<br>
6) Explain in detail about Cascading Style Sheets with suitable examples. May 2014/May 2016)
CSS are powerful mechanism for adding styles (e.g. Fonts, Colors, Spacing) to web documents.
They enforce standards and uniformity throughout a web site and provide numerous attributes to create
dynamic effects.
The advantage of a style sheet includes the ability to make global changes to all documents from a single
location. Style sheets are said to cascade when they combine to specify the appearance of a page.
To create an inline style
Add the style attribute to the HTML tag.
The style declaration must be enclosed within double quotation marks.
To create an embedded style
Insert a <style> tag within the head section of HTML file.
Within the <style> tag, enclose the style declarations need to the entire Web page.
The style sheet language identifies the type of style used in the document.
The default and the most common language is “text/css” for use with CSS.
To create an External styles
Create a text file containing style declarations
Create a link to that file in each page of the Web site using a <link> tag.
Specify the link attributes, such as href, rel, and type.
Link a style sheet, the value of the href attribute should be the “URL” of the linked document, the value of
the rel attribute should be “stylesheet” and the value of the type attribute should be “text/css”.
EXTERNAL.CSS:
body{ background-color: gray;}
p { color: blue; }
EXTERNAL.HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="EXTERNAL.css" /><!—Link tag for External CSS-->
</head>
<body>
<h3> A White Header </h3>
<p> This paragraph has a blue font.
The background color of this page is gray because
we changed it with CSS! </p>
</body>
</html>
INTERNAL.HTML:
<html>
<head>
<style> <!—Style tag for Internal CSS-->
body { background-color: blue; }
p { color: white; }
</style>
</head>
<body>
<h2>Internal CSS</h2>
<p>This page uses internal CSS. Using the style tag we are able to modify
the appearance of HTML elements.</p>
</body>
</html>
INLINE.HTML:
<html>
<head>
</head>
<body>
<h2>InLINE CSS</h2>
<p style="color:sienna;margin-left:20px"><!—Style Attribute(INLINE)-->
This page uses INLINE CSS. Using the style ATTRIBUTE we are able to modify
the appearance of HTML elements.
</p>
</body>
</html>
7) i) Explain the features of cascading style sheet.
CSS stands for Cascading style sheets, which is a type of web language, called style sheet language which
standardizes the layout throughout a website. Therefore used for describing the look and formatting of a
document, from document presentation, including elements such as the layout, colours, and fonts. It’s
commonly used to style web pages, written in HTML and XHTML.
Using CSS mainly enables the separation of document content, focusing on the appearance and formatting.
The separation can improve content accessibility, provide more flexibility and can control the presentation
characteristics, to suit specific requirements. CSS also functions the layout of a website, it can reduce the
size, clutter and load time of web pages. Additionally it enables multiple pages to share formatting and also
reduces complexity and repetition in the structural content. Also, without CSS, a webpage can become
teeming with tables nested inside other tables, which causes the speed of a website to be slow, therefore
using CSS can also improve the speed of a webpage [1]. CSS additionally prevents clutter, it organizes the
web code, it makes it simple and straightforward, this also creates fast loading. As well, CSS permits web
pages to be displayed and understood, even if the CSS is not working, or removed. It is also supported well
by most modern web browsers.
ii) Explain any eight CSS text properties.
Color
You can set the color of text with the following:
color: value;
Possible values are
St. Joseph’s College of Engineering MCA 40
MC5303 Web Programming Essentials 2018-19
color name – example:(red, black…)
hexadecimal number – example:(#ff0000, #000000)
RGB color code – example:(rgb(255, 0, 0), rgb(0, 0, 0))
Letter Spacing
You can adjust the space between letters in the following manner. Setting the value to 0, prevents the text
from justifying. You can use negative values.
letter-spacing: value;
Possible values are
normal
length
Example:
These letters are spaced at 5px.
Text Align
You can align text with the following:
text-align: value;
Possible values are
left
right
center
justify
Examples:
This text is aligned left.
This text is aligned in the center.
This text is aligned right.
This text is justified.
Text Decoration
You can decorate text with the following:
text-decoration: value;
Possible values are
none
underline
overline
line through
blink
Examples:
This text is underlined.
This text is overlined.
This text has a line through it.
This text is blinking (not in internet explorer).
Text Indent
You can indent the first line of text in an (X)HTML element with the following:
text-indent: value;
Possible values are
length
percentage
Examples:
This text is indented 10px pixels.
Text Transform
You can control the size of letters in an (X)HTML element with the following:
text-transform: value;
Possible values are
none
capitalize
lowercase
White Space
You can control the whitespace in an (X)HTML element with the following:
white-space: value;
Possible values are
normal
pre
nowrap
Word Spacing
You can adjust the space between words in the following manner. You can use negative values.
word-spacing: value;
Possible values are
normal
length
Example:
These words are spaced at 5px.
<body>
<p>This is a paragraph with no specified margins.</p>
<p class="margin">This is a paragraph with specified margins.</p>
</body>
</html>
This is a paragraph with no specified margins.
This is a paragraph with specified margins.
Padding means the space between the contents and its border. Various properties of padding are padding-
left, padding-right, padding-top and padding-bottom. These values can also be given in ps or in in.
<!DOCTYPE html>
<html>
<head>
<style>
p
St. Joseph’s College of Engineering MCA 42
MC5303 Web Programming Essentials 2018-19
{
background-color:yellow;
}
p.padding
{
padding-top:25px;
padding-bottom:25px;
padding-right:50px;
padding-left:50px;
}
</style>
</head>
<body>
<p>This is a paragraph with no specified padding.</p>
<p class="padding">This is a paragraph with specified paddings.</p>
</body>
</html>
This is a paragraph with no specified padding.
This is a paragraph with specified padding’s.
9) Explain is CSS positioning? Explain it with illustrative examples.
Positioning
The CSS positioning properties allow you to position an element. It can also place an element behind
another, and specify what should happen when an element's content is too big.
Elements can be positioned using the top, bottom, left, and right properties. However, these properties will
not work unless the position property is set first. They also work differently depending on the positioning
method.
There are four different positioning methods.
Static Positioning
HTML elements are positioned static by default. A static positioned element is always positioned
according to the normal flow of the page.
Static positioned elements are not affected by the top, bottom, left, and right properties.
Fixed Positioning
An element with fixed position is positioned relative to the browser window.
It will not move even if the window is scrolled:
Example
p.pos_fixed
{
position:fixed;
top:30px;
right:5px;
}
Note: IE7 and IE8 support the fixed value only if a !DOCTYPE is specified.
Fixed positioned elements are removed from the normal flow. The document and other elements behave
like the fixed positioned element does not exist.
Fixed positioned elements can overlap other elements.
Relative Positioning
A relative positioned element is positioned relative to its normal position.
Example
h2.pos_left
{
position:relative;
left:-20px;
}
h2.pos_right
{
position:relative;
10) i) Explain how to use CSS to control the style and layout of multiple web pages.(May 2015)
Click the link in brackets above the 'Applied Rules' pane to quickly open your .css file. (See Fig 3
below)
In the 'CSS Properties' Task Panel which can be opened under the 'Panels' Menu you can start typing the
selector - body - and the IntelliSense you set up in the configuration section above now comes into play.
The 'IntelliSense' dialog box will appear and allow you to select body, if you then insert { the end tag will
also be inserted } and IntelliSense will suggest properties and then values for you to insert.
Once you have just one style inserted CSS Properties will be populated and you can select and make any of
the styles using the CSS Properties Panel.
Modify a Style
When you want to Modify the properties of a style you can do so from a variety of locations.
CSS Properties Task Pane - Enables you to edit only styles that the current web page uses. (This means
styles you can select in Code view or any style in an open .CSS file.
Apply Styles Task Pane - Enables you to edit any style contained in the Style Sheets of the Current web
page. (Also styles that web page does not use)
Manage Styles Task Pane - Enables you to edit any style similar to Apply Styles Task Pane
Modify Style dialog box enables you to design a new or existing style and preview the style's appearance
as you design it.
Please visit Modify the properties of a style to find out how to do so. You might also want to Rename a
Style.
Apply a Style
The 'Apply Styles' panel enables you to create, modify, apply, remove, or delete styles, and attach or
remove an external CSS. The panel identifies style types, and shows you if the style is used in the current
web page and by the current selection.
When you want to Apply a class or id selector from your style sheet you can use one of the following:
Apply Styles Panel
Manage Styles Panel
Style Toolbar
The difference between them is that 'Apply Styles' Panel allows multiple styles to a selection whilst
the 'Manage Styles' Panel allow only one, with the 'Style Toolbar' it enables you to name and apply new
undefined styles within your page in a timely manner.
To apply a style
In Design view or Code view, in your web page, select the item you want to apply a style to.
Do one of the following:
To apply multiple existing styles, in the 'Apply Styles' panel, press CTRL while you click each style that
you want.
To apply a single existing style in the 'Apply Styles' panel, click the class or ID style you want.
To apply a single existing style in the 'Style toolbar', in either the Class or ID drop-down box, click the
style you want.
To apply a single existing style in the 'Manage Styles' panel, right-click the class or ID style you want,
and in the shortcut menu, click 'Apply Style'.
To create and apply a new style without defining any properties, in the Style toolbar, in either the Class or
ID box, type a unique name for the new style.
Delete a style from a cascading style sheet
When you no longer need a particular style, you can delete the style from your cascading style sheet (CSS)
by using the Apply Styles panel or Manage Styles panel, depending upon the type of style you want to
delete.
Attach or detach an external cascading style sheet
The first column is set to 25% of the width of the browser window. The second column is set to 75% of the
width of the browser window. The document "frame_a.htm" is put into the first column, and the document
"frame_b.htm" is put into the second column:
<frameset cols="25%,75%"> <frame src="frame_a.htm" /> <frame src="frame_b.htm" />
</frameset>
Note: The frameset column size can also be set in pixels (cols="200,500"), and one of the columns can be
set to use the remaining space, with an asterisk (cols="25%,*").
Basic Notes - Useful Tips
Tip: If a frame has visible borders, the user can resize it by dragging the border. To prevent a user from
doing this, you can add noresize="noresize" to the <frame> tag.
Note: Add the <noframes> tag for browsers that do not support frames.
Important: You cannot use the <body></body> tags together with the <frameset></frameset> tags!
However, if you add a <noframes> tag containing some text for browsers that do not support frames, you
will have to enclose the text in <body></body> tags! See how it is done in the first example below.
Create a Frame
<html>
<head>
Attributes
Like all other HTML elements, this element supports the global attributes.
autoplay
A Boolean attribute; if specified, the video automatically begins to play back as soon as it can do so
without stopping to finish loading the data.
autobuffer
A Boolean attribute; if specified, the video will automatically begin buffering even if it's not set to play
automatically. Use this attribute only when it is very likely that the user will watch the video. The video is
buffered until the media cache is full.
buffered
An attribute you can read to determine the time ranges of the buffered media. This attribute contains
a TimeRanges object.
controls
If this attribute is present, the browser will offer controls to allow the user to control video playback,
including volume, seeking, and pause/resume playback.
St. Joseph’s College of Engineering MCA 47
MC5303 Web Programming Essentials 2018-19
crossorigin
This enumerated attribute indicates whether to use CORS to fetch the related image. CORS-enabled
resources can be reused in the <canvas> element without being tainted. The allowed values are:
anonymous
Sends a cross-origin request without a credential. In other words, it sends the Origin: HTTP header
without a cookie, X.509 certificate, or performing HTTP Basic authentication. If the server does not give
credentials to the origin site (by not setting theAccess-Control-Allow-Origin: HTTP header), the image
will be tainted, and its usage restricted.
use-credentials
Sends a cross-origin request with a credential. In other words, it sends the Origin: HTTP header with a
cookie, a certificate, or performing HTTP Basic authentication. If the server does not give credentials to
the origin site (through Access-Control-Allow-Credentials: HTTP header), the image will be tainted and its
usage restricted.
When not present, the resource is fetched without a CORS request (i.e. without sending theOrigin: HTTP
header), preventing its non-tainted used in <canvas> elements. If invalid, it is handled as if the enumerated
keyword anonymous was used. See CORS settings attributesfor additional information.
height
The height of the video's display area, in CSS pixels.
loop
A Boolean attribute; if specified, we will, upon reaching the end of the video, automatically seek back to
the start.
muted
A Boolean attribute which indicates the default setting of the audio contained in the video. If set, the audio
will be initially silenced. Its default value is false, meaning that the audio will be played when the video is
played.
played
A TimeRanges object indicating all the ranges of the video that have been played.
preload
This enumerated attribute is intended to provide a hint to the browser about what the author thinks will
lead to the best user experience. It may have one of the following values:
none: indicates that the video should not be preloaded.
metadata: indicates that only video metadata (e.g. length) is fetched.
auto: indicates that the whole video file could be downloaded, even if the user is not expected to use it.
the empty string: synonym of the auto value.
If not set, its default value is browser-defined (i.e. each browser may have its default value). The spec
advises it to be set to metadata.
Usage notes:
The autoplay attribute has precedence over preload. If autoplay is specified, the browser would obviously
need to start downloading the video for playback.
The specification does not force the browser to follow the value of this attribute; it is a mere hint.
poster
A URL indicating a poster frame to show until the user plays or seeks. If this attribute isn't specified,
nothing is displayed until the first frame is available; then the first frame is shown as the poster frame.
src
The URL of the video to embed. This is optional; you may instead use the <source> element within the
video block to specify the video to embed.
width
The width of the video's display area, in CSS pixels.
Events
The <video> element can fire many different events.
Examples
<!-- Simple video example -->
<video src="videofile.ogg" autoplay poster="posterimage.jpg">
Sorry, your browser doesn't support embedded videos,
but don't worry, you can <a href="videofile.ogg">download it</a>
and watch it with your favorite video player!
</video>
Another important thing to note about HTML is that all HTML user agents (this is a catchall term
for programs that read HTML, including web browsers, search engine web crawlers, and so forth)
have extremely lenient error handling. Many technically illegal constructs, like misnested tags or
bad attribute names, are allowed or safely ignored. This error-handling is relatively consistent
between browsers. But there are lots of differences in edge cases, because this error handling
behavior is not documented or part of any standard. This is why it is a good idea to validate your
documents.
XML and XHTML are quite different. XML (eXtensible Markup Language) grew out of a desire
to be able to use more than just the fixed vocabulary of HTML on the web. It is a meta-markup
language, like SGML, but one that simplifies many aspects to make it easier to make a generic
parser. XHTML (eXtensible HyperText Markup Language) is a reformulation of HTML in XML
syntax. While very similar in many respects, it has a few key differences.
First, XML always needs close tags, and has a special syntax for tags that don’t need a close tag. In
HTML, some tags, such as img are always assumed to be empty and close themselves. Others, like
p may close implicitly based on other content. And others, like div always need to have a close tag.
In XML (including XHTML), any tag can be made self-closing by putting a slash before the code
angle bracket, for example <img src="funfun.jpg"/>. In HTML that would just be <img
src="funfun.jpg">
Second, XML has draconian error-handling rules. In contrast to the leniency of HTML parsers,
XML parsers are required to fail catastrophically if they encounter even the simplest syntax error
in an XML document. This gives you better odds of generating valid XML, but it also makes it
very easy for a trivial error to completely break your document.
HTML-compatible XHTML
When XML and XHTML were first standardized, no browser supported them natively. To enable
at least partial use of XHTML, the W3C came up with something called “HTML-compatible
XHTML”. This is a set of guidelines for making valid XHTML documents that can still more or
less be processed as HTML. The basic idea is to use self-closing syntax for tags where HTML
doesn’t want a close tag, like img, br or link, with an extra space before the slash. So our ever-
popular image example would look like this: <img src="funfun.jpg" />. The details are described
in the Appendix C of the XHTML 1.0 standard.
It’s important to note that this is kind of a hack, and depends on the de facto error handling
behavior of HTML parsers. They don’t really understand the XML self-closing syntax, but writing
things this way makes them treat / as an attribute, and then discard it because it’s not a legal
attribute name. And if you tried to do something like <div />, they wouldn’t understand that the div
is supposed to be empty.
There are also many other subtle differences between HTML and XHTML that aren’t covered by
this simple syntax hack. In XHTML, tag names are case sensitive, scripts behave in subtly
different ways, and missing implicit elements like <tbody> aren’t generated automatically by the
parser.
So if you take an XHTML document written in this style and process it as HTML, you aren’t really
getting XHTML at all – and trying to treat it as XHTML later may result in all sorts of breakage.
UNIT III
1) Explain the core features of javascript in detail.
– Whitespace is generally ignored in JavaScript statements and between JavaScript statements but not
always consider
• x = x + 1 same as x=x + 1
Statements
alert(x);
alert(x);
Blocks
Variables
Variables store data in a program
The name of a variable should be unique well formed identifier starting with a letter and followed by
letters or digits
Variable names should not contain special characters or white space
– X versus sum
– var x;
– var x = 5;
– var x, y = 5, z;
Weak Typing
JavaScript is a weakly type language meaning that the contents of a variable can change from one type to
another.
– Some languages are more strongly type in that you must declare the type of a variable and stick with it.
Example of dynamic & weak typing a variable initially holding a string can later hold a number
= "hello"; x = 5; x = false;
You may run into significant problems with type conversion between numbers and strings use functions
like parseFloat() to deal with these problems
– Prompt demo
Composite Types
JavaScript supports more advanced types made up of a collection of basic types.
Arrays
Defining arrays
Arrays
Access arrays by index value
– myArray[3] = "Hello";
– Given new Array(4) you have an array with an index running from 0 – 3
alert(myArray2 .length);
Objects
Underneath everything in JavaScript are objects.
The various data types called properties and functions called methods are accessed using a dot notation.
objectname.propertyname
We have actually been using these ideas already, for example document.write( hello ) says using the
document object invoke the write() method and give it the string “hello” this results in output to the string
Given the need to use objects so often shortcuts are employed such as the with statement
with (document)
{
We also see the use of the short cut identifier this when objects reference themselves
Expressions and Operators
Make expressions using operators in JavaScript
Basic Arithmetic
Comparison
More Operators
String Operator
Flow Control
• if (expression) or if (expression)
true-case true-case;
Else
false-case;
if (x > 10)
More on If Statements
You can use { } with if statements to execute program blocks rather than single
statements
if (x > 10)
{
alert("X is bigger than 10");
St. Joseph’s College of Engineering MCA 53
MC5303 Web Programming Essentials 2018-19
alert("Yes it really is bigger");
}
• Be careful with ;’s and if statements
if (x > 10);
alert("I am always run!? ");
aScript 1 2
Switch Statements
If statements can get messy so you might consider using a switch statement instead
switch (condition)
{
case (value) : statement(s) break;
…
default: statement(s);
}
The switch statement is not supported by very old JavaScript aware browsers (pre-JavaScript 1.2), but
today this is not such an important issue
Switch Example
Loops
Syntax of while:
while(condition) statement(s)
Example:
var x=0;
document.write("<br />"); x = x + 1;
document.write("Done");
vaScript 1 2
Do Loop
St. Joseph’s College of Engineering MCA 54
MC5303 Web Programming Essentials 2018-19
• The difference between loops is often when the loop condition check is made, for example
var x=0; do
document.write(x); x = x + 1;
} while (x < 10);
In the case of do loops the loop always executes at least once since the check happens at the end of the
loop
For Loop
The most compact loop format is the for loop which initializes, checks, and increments/decrements all in a
single statement
for (x=0; x < 10; x++)
{
document.write(x);
}
With all loops we need to exercise some care to avoid infinite loops. See example
avaScript 1 2
For/In Loop
One special form of the for loop is useful with looking at the properties of an object. This is the for/in loop.
We will find this construct useful later on when looking at what we can do with a particular object we are
using
Loop Control
We can control the execution of loops with two statements: break and continue
var x=0;
while (x < 10)
{
x = x + 1; if (x == 3) continue;
document.write("x = "+x); if (x == 5)
break;
}
2
Functions
For example
function add(x, y)
}
Jacript 1 2
We can then invoke a function using the function name with ( )’s
result = add(a,b);
Variables are passed to function by value so you must use return to send things back.
You can return a value or not from a function and you can have as many return statements as you like
Input/Output in JavaScript
– Alert
alert("Cheese hater");
– Prompts
– document.write()
St. Joseph’s College of Engineering MCA 56
MC5303 Web Programming Essentials 2018-19
– document.writeln()
Since we are writing to an (X)HTML document you may write out tags and you will have to consider the
white space handling rules of (X)HTML
Every variable has a data type that indicates what kind of data the variable holds
Weak Typing
JavaScript is a weakly type language meaning that the contents of a variable can change from one type to
another.
– Some languages are more strongly type in that you must declare the type of a variable and stick with it.
Example of dynamic & weak typing a variable initially holding a string can later hold a number
= "hello"; x = 5; x = false;
– Prompt demo
You can also use the typeof operator to figure out type
• Be aware that using operators like equality or even + may not produce expected results
x=5;
Produces a rather interesting result. We see the inclusion of a type equality operator (===) to deal with this
Composite Types
JavaScript supports more advanced types made up of a collection of basic types.
Arrays
– An ordered set of values grouped together with a single identifier
2) Explain the operators with examples.
Operators
An operator generally performs some kind of calculation (operation) or comparison with two values(the
value on each side of an operator is called operand) to reach a third value.
Type of operator: Arithmetic Operator, Comparison Operator, Assignment Operators, Bitwise Operator
Increment and Decrement Operator, Logical Operator
Basic operators
Operator Description Example Result
++ Increment x=5 x=6
x++
The javaScript assignment operator is the symbol =. Thus the javascript statement x = a+b
Comparison Operators in Javascript.
Decision-making has its own operators, which allow anyone to test conditions. There are many comparison
operators of which most useful are summarized in the following table
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
Logical operators
Javascript allows us to use multiple conditions; to do the logical operators AND, OR, and NOT
are in use. The symbols for these are listed below
function total(a,b)
{
result=a+b
return result
}
When you call this function you must send two arguments with it:
sum=total(2,3)
The returned value from the function (5) will be stored in the variable called sum.
Multiple-Subscripted Arrays
Multiple-subscripted arrays with two subscripts often are used to represent tables of values consisting of
information arranged in rows and columns.
To identify a particular table element, we must specify the two subscripts; by convention, the first
identifies the element‘s row, and the second identifies the element‘s column. Arrays that require two
subscripts to identify a particular element are called double-subscripted arrays (also called two-
dimensional arrays).
Multiple-subscripted arrays can have more than two subscripts. JavaScript does not support multiple-
subscripted arrays directly, but does allow the programmer to specify single-subscripted arrays whose
elements are also single-subscripted arrays, thus achieving the same effect.
Every element in array a is identified by an element name of the form a[i][j]; a is the name of the array,
and i and j are the subscripts that uniquely identify the row and column, respectively, of each element in a.
The names of the elements in the first row all have a first subscript of 0; the names of the elements in the
fourth column all have a second subscript of 3. Multiple-subscripted arrays can be initialized in
declarations like a single-subscripted array. Array b with two rows and two columns could be declared and
initialized with the statement
var b = [ [ 1, 2 ], [ 3, 4 ] ];
The values are grouped by row in square brackets. So, 1 and 2 initialize b[0][0] and b[0][1], and 3 and 4
initialize b[1][0] and b[1][1]. The interpreter determines the number of rows by counting the number of
sub-initializer lists (represented by sets of square brackets) in the main initializer list. The interpreter
determines the number of columns in each row by counting the number of initializer values in the sub-
initializer list for that row. Multiple-subscripted arrays are maintained as arrays of arrays. The declaration
var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];
creates array b with row 0 containing two elements (1 and 2) and row 1 containing three
elements (3, 4 and 5).
8) Explain any three objects that can be defined in JavaScript with the help of examples. (May 2016)
Javascript objects has collection of related properties and methods that can be used to manipulate a
certain kind of data.
They are three types of objects
1) Math object
The math object provides a number of useful mathematical functions and number manipulation methods.
There is no need to declare a variable as Math object or define a new math object before being able to use
it, making it a little bit easier to use.
Some math objects are as following
1) abs() Method: The abs() method returns the absoulate value of the number passes as its parameter.
Essentially , this means that it returns the positive value of the number. So -1 is returned as 1, -4 as 4 and
so on. However , 1 would be returned as 1 because it’s already positive.
2) ceil() Method: The ceil() method always round a number up to the next largest whole number or integer.
So 10.01 becomes 11 and 9.99 becomes -9(because -9 is greater than -10). Ceil() method has just one
parameter, namely the number you want rounded up.
3) floor() Method: Like the ceil() method, the floor method removes any numbers after the decimal point,
and returns a whole number or integer. The difference is that floor() always rounds the number down, so if
we pass 10.01 we would be returned 10, and if we pass9.99 , we will see -10returned.
St. Joseph’s College of Engineering MCA 63
MC5303 Web Programming Essentials 2018-19
4) round Method: The round method is very similar to ceil() and floor(), except that instead of always
rounding up or rounding down, it rounds up only if the decimal part is 0.5 or greater , and rounds down
otherwise.
5) random() Method: The random method returns a random floating point number in the range between 0
and 1 , where 0 is included and 1 is not . This can be very useful for displaying random number banner
images for writing a javascript game.
Date Object
The date object handles everything to do with date and time in javascript. Using it , we can find out the
date time now, store our own dates and time, do calculations with these dates , and converts the dates into
strings.
2) Getting Date Values: it is all very nice having stored a date, but how to we get the information out
again? Well , we just use the get methods. These are summarized in the following table
Method Returns
getDate() The day of the month
getDay() The day of the week as an integer, with Sunday as 0, Monday as 1 and so on.
getmonth() The month as an integer, with January as 0, February as 1 and so on.
getFullYear() The year as a four-digit number
toDateString() Returns the full date based on the current time zone as a human-readable string.
3) Setting Date values: To change part of a date into date object , we have a group of set functions, which
pretty much replicate the get functions described earlier , except that we are setting not getting values.
Method Description
setDate() The date of the month is passed in as parameter to set the date
setMonth() The month of year is passed in as an integer parameter, whose 0 is January, 1 as
Feburary and so on.
setallYear() This sets the year to the four digit integer number passed in as a parameter.
Document object model
Every web page resides a browser window which can be considered as an object.
A document object represents the HTML documents that is displayed in that window. The document object
has various properties that refer to other objects which allow access to and modification of docment
content.
The way that document content is accessed and modified is called the Document Object Model. The
Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a
web document.
Window Object: Top of the hierarchy. It is the outmost element of the object hierarchy.
Document Object: Each HTML document that gets loaded into a window becomes a document object. The
document contains the content of the page.
Form Object: Everything enclosed in the <form>… </form> tags sets the form object.
Form Control Elements: The form object contains all the elements defined for that object such as text
fields, buttons, radio buttons, and checkboxex.
Here is a simple hierarchy of few important objects:
Window
Frame Parent Self top
9) i) Write short notes on Inline Frames and Applied Frames.(or) Explain any four JavaScript window
methods to control windows. (May 2015)
Javascript includes powerful features for working with browser windows.
Creating a new window
One of the most convenient uses for the window object is to create a new window. You can do this to
display a document , eg: the instructions for a game- without clearing the current window.
You can create a new browser window with the window.open() method. A typical statement to open a new
window looks like this:
WinObj = window.open(“URL”,”windowName”,”Feature List”);
The following are the compondents of window.open() statement
1) The WinObj variable is used to store the new window object. You can access methods and properties of
the new object by using the name.
2) The first parameter of the window.open() method is a URL, which will be loaded into the new window.
If it is left blank, no web page will be loaded.
3) The second parameter specifies a window name (here window name). this is assigned to the window
object’s name property and is used to refer the window.
4) the third parameter is a list of optional features , separated by commas.
Opening and closing window
You can close windows as well. The window.close() method closes a window.
Frames
A frame is a special type of window that can display multiple independently scrollable frames on a single
screen, each with its own distinct URL. Frames can point to different URL’s and be targeted by other
URL’s , all within the same window. A series of frames makes up a page.
The following diagram shows a window containing three frames:
Music Club Alen sing a song
Artists
Jazz
-T.Alen
-j.jack
Soul
-b.britto
Alphabetical by category Musician Description
This frame is named navigateFrame
Creating a frame
You can create a frame by using the <FRAMESET> tag in an HTML document.
Example
<FRAMESET ROWS = “90%,10%>
<FRAMESET COLS = “30%,70%>
<FRAME SRC = category.html NAME = “list frame”>
<FRAME SRC = titles.html NAME = “contentFrame”>
</FRAMESET>
<FRAME SRC = navigate.html NAME = “navigateFrame”>
</FRAMESET>
DOCUMENTS
Document object is an object that is created by the browser for each new HTML page(document) that is
viewed. By doing this, javascript gives you access to a number of properties and methods that can affect
the document in various ways.
Document object has a number of properties associated with it, which are following:
Property Description
formName Not a property itself, but creates a new property with each named form placed in the
document
Forms An array of all form tags in a document
Frames An array of all frames used in the document.
Height Returns the height, in pixels, of the body element of the document.
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if(x==null||x== "")
{
alert("First name must be filled out ");
return false;
}
}
</script>
</body>
<form name = "myForm" action = "demo_form.asp" onsubmit= "return validateForm()" method = "post">
First name:<input type = text" name = "fname">
<input type = "submit" value = "Submit">
</form>
</body>
</html>
10) Designing Quiz Application Personal Information System/ Using JavaScript
<form name = "myform">
Which is the largest animal on land?<br>
Aardvark <input type = "radio" name = "rad1" onclick = "getAnswer('1a', '1')">
Whale <input type = "radio" name = "rad1" onclick = "getAnswer('1b', '2')">
Elephant <input type = "radio" name = "rad1" onclick = "getAnswer('1c', '3')">
Rhinosaurus <input type = "radio" name = "rad1" onclick = "getAnswer('1d','4')">
<br><br>
<div id = "para"><div>
</form>
</script>
Output:
11) Write JavaScript code to check whether the user has entered a valid e-mail address and a valid date.
VALIDATION.HTML:
<html>
<head>
<script type="text/javascript">
var fl=1;
function check()
{
var n=document.forms[0].elements[0].value;
var re=new RegExp("^[0-9]");
xyz.innerText="";
if(n.length<1)
{
xyz.innerText="invalid user name";
fl=0;
}
if(re.test(n))
{
xyz.innerText="User name should not start with a digit";
fl=0;
}
}
if(m1=="")
{
p1.innerText="please enter email id";
fl=0;
}
if(re1.test(m1))
{
p1.innerText="mail id should not start with a digit";
fl=0;
}
}
function addr()
{
p2.innerText="";
var adr=document.getElementById("ad").value;
if(adr=="")
{
p2.innerText="field should be filled";
fl=0;
}
}
function showit()
{
if(fl==0)
alert("Your registration was not successful");
<td>
<p id="xyz"></p>
</td>
</tr>
<tr>
<td>
<h3 align="center">
Password
:
<input type="password" id="pwd" onBlur="check1()"></h3>
</td>
<td>
<p id="xyz1"></p>
</td>
</tr>
<tr>
<td>
<h3 align="center">Confirm password:
<input type="password" id="pwd1" onBlur="check2()"></h3>
</td>
<td>
<p id="xyz2">
</td>
</tr>
<tr>
<td>
<h3 align="center">
&n
bsp; &nbs
p; Email
Address :
<input type="text" name="mail" onBlur="email()"> @
<select size="1" name="mail1" tabindex="9">
<option value="1">gmail</option>
<option value="1">yahoo</option>
<option value="1">rediffmail</option>
<option value="1">hotmail</option>
<option value="1">msn</option></select> .
<select size="1" name="mail2" tabindex="9">
<option value="1">com</option>
<option value="1">co.in</option>
</td>
<td>
<p id="p1"></p>
</td>
</tr>
<tr>
<td>
<br>
<h3 align="center">
Address &
nbsp; :
<input type="text" name="ad" onBlur="addr()"></h3>
</td>
<td>
<p id="p2"></p>
</td>
</tr>
<tr>
<td>
<h3 align="center">
Line1 &nb
sp; :
<input type="text" name="l1"></h3>
</td>
</tr>
<tr>
<td>
<h3 align="center">
Line2 &nb
sp; :
<input type="text" name="l2"></h3>
</td>
</tr>
<tr>
<td>
<h3 align="center">
Pin  
; :
<input type="text" name="pin"></h3>
</td>
</tr>
</table>
<br>
<h3 align="center"><input type="submit" value="submit" onClick="showit()">
<input type="reset" value="reset">
</h3>
</form>
</body>
</html>
OUTPUT:
Login: Karups
13) Explain the different types of looping statements in JavaScript. (May 2016)
Refer the first question answer.
UNIT IV
1)Explain Browser Management in detail. (or) What methods are used for browser Management in
JavaScript? Explain (MAY 2015)
Javascript can be used to manage the browser and user experience
All browser offers ways to manage private data, which can range from a record of sites one has viewed to
copies of web pages stored for the purposes of faster load times on subsequent visits. Each browser
provides a way to peruse this data, as well as various methods to remove it from computer or portable
device. Theses browsers also give the ability to surf the web without saving any of these sensitive data
components.
Although each browser may have its own unique name for certain private data components, one will find
that terms are interchangeable and that all browsers store the same items. There are some exceptions , that
each browser represents items in different ways.
Navigator Object
The navigator objects of javascript shows how to use it to perform browser detection, whether the subject
is Firefox, Internet Explorer, Opera, etc.
Javascript’s navigator objects provides properties that indicate the type of browser and other useful
information about the user accessing the page.
The navigator object of javascript contains the following core properties.
Properties Description
appCodeName The code name of the browser
appName The name of the browser
appVersion Version information for the browser
cookieEnabled Boolean that indicates whether the browser has
cookies enabled.
Language Returns the default language of the browser
version.
online Determines whether the browser is online
Platform Returns for which platform the browser is
complied.
Product Returns the engine name of the browser.
userAgent Returns the user-agent header sent by the
St. Joseph’s College of Engineering MCA 71
MC5303 Web Programming Essentials 2018-19
browser to the server.
<!DOCTYPE html>
<html>
<body>
<div id="example"></div>
<script>
txt="<p>Browser CodeName:"+navigator.appCodeName+"</p>";
txt+="<p>Browser Name:"+navigator.appName+"</p>";
txt+="<p>Browser Version:"+navigator.appVersion+"</p>";
txt+="<p>Cookies Enabled:"+navigator.cookieEnabled+"</p>";
txt+="<p>Browser Language:"+navigator.language+"</p>";
txt+= "<p>BrowserOnline:"+navigator.OnLine+"</p>";
txt+="<p>Platform:"+navigator.platform+"</p>";
txt+="<p>User-agent header:"+navigator.userAgent+"</p>";
txt+="<p>User-agentlanguage:"+navigator.systemLanguage+"</p>";
document.getElementById("example").innerHTML= txt;
</script>
</body>
</html>
BROWSER DETECTION
Anyone who has built more than a few web pages has surely come across some of the nyumerous
differences between browser types and versions. A page that looks perfect on one computer screen does
not look quite the same on other computer screen. It looks vastly different that is small shift of content or
container size.
Hence user simplifies their site technology to the so called lowest common denominator In order to meet of
older browsers, often lacking support for even CSS or javascript and viewing pages in a low resolution
environment.
Falling somewhere in between these extremes is the more adaptive type of site that modifies itself to suit
the browser’s capabilities or indoicates to users their inability to use the site. This “sense and adapt” cocept
is often termed browser detection or browser sniffing. It is integral part of javascript tasks of any
complexity.
Browser sniffing is a technique used in website and web applications in order to determine the web
browser a visitor is using, and to serve bowser-appropriate content to the vistor.
They are different types of detection
Information detection
Technology detection
Javascript detection
Plug-in Detection
Visual detection
Information detection
When using javascript to detect the capabilities of web site or application’s visitors, one can break up the
useful detectable information in four categories.
Technology detection
Javascript detection
Javascript support is probably the easiest technology to detect. If a script does not run, this condition
implicitly shows that the browser does not support javascript or that it is turned off. It have two types
javascript version and object detection.
Visual detection
The screen object encapsulates information about the display on which the window is being rendered,
including the size of the screen and the number of colors that it can display. The following are the
commonly used screen properties.
Property Description
avaailHeight Returns the height of the screen
availWidth Returns the width of the screen
colorDepth Returns the bit depth of the color palette for
displaying images
Height Returns the total height of the screen
pixelDepth Returns the color resolution
Width Returns the total width of the screen.
Browser control
Using the window object it is possible to change window appearance. For example one might scroll or
resize the window using window.scrollTo() or window.resizeTo() or the set the browser status message
using window.status or window.defaultStatus.
For more control , one might consider opening a new window (window.open) and removing the browser ‘s
or even going full screen.
State Management
Cookies are data, stored in small text files on computer. When a web server has sent a web page to a
browser , the connection is shut down and the server forgets everything about the user.
Web pages are not composed solely of text, but generally include a variety of depedent media items such
as images, videos , audioclips, and multimedia elements.
Image handling
One can use javascript to get at and manipulate images. This may involve creating new images, setting up
an array of images , chaning the source attribute in the <body> tag or just doing some simple animation
with them.
Any images user places between the two <body> tags of HTML pages can be seen by javascript. This is
because whenever one add a picture with the IMG tag it is placed in a collection , which is a sort of array.
The first picture that the browser can see , the one closet to the opening BODY tag, is place at position 0 in
the collection. The second picture will be placed at position 1, the third at position 2 etc. for web page,
move the two <script> tags inside the <body> of the html:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>IMAGE COLLECTION</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE = "JAVASCRIPT">
</SCRIPT>
</BODY>
</HTML>
<BODY>
<IMG SRC = "C:\Documents and Settings\BOSS\Desktop\DSC06396.JPEG">
<P>
<IMG SRC = "C:\Documents and Settings\BOSS\Desktop\DSC06397.JPEG">
<P>
<INPUT TYPE = "BUTTON" VALUE = "GO" ONCLICK = "IMAGE_TEST()">
<P>
<LABLE ID = "LABEL_1>IMAGE NAMES</LABEL>
<SCRIPT LANGUAGE = "JAVASCRIPT">
</SCRIPT>
</BODY>
ANIMATION
One can use javascript to create a complex animation which includes but not limited to:
Fireworks.
Fade effect.
Roll-in or Roll-out.
Page-in or Page-out.
Object movements.
Javascript provides following two functions to be frequently used in animation programs
Set(Timeout(function ,duration): this function calls function after duration milliseconds from now.
setInterval(function, duration): this function calls function after every duration milliseconds.
clearTimeout(setTimeout_varaible); this function calls clear any timer set by the setTimeout() functions.
Drawing lines
<html>
<head>
<style>
body
{
margin:0px;
padding:0px;
}
</style>
</head>
<body>
<canvas id="myCanvas"width="578" height="200"></canvas>
<script>
St. Joseph’s College of Engineering MCA 74
MC5303 Web Programming Essentials 2018-19
var canvas = document.getElementById("my Canvas");
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(100,150);
context.lineTo(450,50);
context.linewidth = 20;
context.strokestyle = '#0000ff';
context.lineCap = 'round';
context.stroke();
</script>
</html>
Script Explanation
In above written script we have created an object Student using new operator. While creating the object we
have written a constructor to which the initializing values are passed as parameter. Then using the variable
this we can access the data properties of the object Student. Similarly the method display is initialized in
this constructor. This method is then invoked in the body section using the dot operator as-
Std_III.display(). Hence as an output we can see the values that gets assigned to the data properties.
Thus we create a collection of objects using the same constructor then it resembles the concept of class in
the object oriented programming. But there is such class concept in javascript , although it supports the
concept of object. Hence javascript is called as object based programming.
4)Explain on object constructor and prototyping.
Javascript provides a special predefined constructor function called Object(), used with the new
keyword, to bulid a genric object. The return value of the Object() constructor is assigned to a variable.
The variable contains a reference to an instance of a new object. Program below create a user-defined
function that will act as a constructor.
Syntax:
Var myobj = new Object();
For example
<html>
<head><title>The object() Constructor</title>
<script type = “text/javascript”>
Var cat = new Object();
Alert(cat);
</script>
<body>
</body>
</html>
Explanation
The Object() constructor creates and returns a reference to a cat object.
The returned value from the Object() constructor is a reference to an object.[object Object] means that the
cat is a descendant of the Object object from which all objects are derived.
Prototyping
In a language such as java or c++ , to create a class as an extension of another, one define the class in such
a way that it inherits the functionality of the higher-level object and overrides whatever functionality
ha/she does not want.
Javascript , on the other hand , provides for a constructor, via object, that allows one to create new onjects.
It is the object constructor that allocates the memory for the object , including all of its properties.
The Object also provides a prototype property that enables to extend nay object, including the built-in-
ones such as String and Number. One uses this prototype to derive new object methods and properties,
rather than class inheritance:
Number.prototype.add = function(val1,val2) {return val1+val2;}
Var num = new Number();
Num.prototype.add = function(val1,val2)
Var sum =num.add(8,3);//sum is 11
This demonstrates of the dynamic nature of Javascript, and how one can add new methods and properties
to objects at runtime. There is a difference between adding a new property or method to an instance of an
The following code is not the same as the preceding code snippet because the add method now applies only
to the object instance, and not to all instances of an object:
Var num = new Number();
Num.add=function(val1,val2){return val1+val2};
Var sum = num.add(8,3);
When anyone extent an object through prototype, the method or property is available to all instances of the
object. When he/she extend an object instance with a new property or method, it is available only to the
instance.
The concept of extending objects via prototyping is best explained through a demonstration.
The following example demonstrates how to extend the employee object by defining a new method, trim,
using the underlying object prototype property. Example
<!DOCTYPE html>
<html>
<body>
<script>
function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}
document.write(fred.salary);
</script>
</body>
</html>
20000
AJAX involves full-page updates. Ie request is made by the client(browser), the server processes the
request and sends the output(usually HTML).
The client renders the HTML page. This way of posting a page will do well with processing a non-
interactive web Form, but what about instances where is expected to be interactive. A key requirement of
such a type of transcation is to have the ability to fill up a partial page, consisting of a field or a set of fields
in a Form, rather than the entire page.
</body>
</html>
Advantages of AJAX
Better Interactivity: AJAX allows easier and quicker interaction between user and website as pages are not
reloaded for
content to be display.
2)Easier Navigation: AJAX application on web-sites can be built to allow easier navigation to users in
comparison to using the traditional back and forward button on a web browser.
Compact: with AJAX, several multi-purpose applications and features can be handled using a single web
page, avoiding the need for clutter with several web pages.
Backed by Reputed Brands: another assuring reason to use AJAX on website is the fact that several
complex web applications are handles using AJAX , google Maps is the most impressive and obvious
example, other powerful , popular scripts such as the vBulltien forum software has also incorporated AJAX
into their latest version.
Disadvantages of AJAX
Back and refresh Button are Rendered Useless: with AJAX as , all functions are loaded on a dynamic page
without the page beging reloaded or more importantly a URL being changed, clicking the back or refresh
button would take you to an entirely different web page or to the beginning of what your dynamic web
page was processing. this is the main drawback behind AJAX but fortunately with good programming
skills this issue can be fixed.
Security constraints: due to security constraints, one can only use to access information from the host that
server the initial page. If anyone needs to display information from server, it is not possible within the
AJAX.
INTRODUCTION
JSON is a syntax for storing and exchanging text information. JSON is smaller than XML and faster and
easier to parse.
JSON is a light weight data interchange format. Rather than attempt to chain references as comma
delimited strings, or have to deal with the complexity (and over head) of XML, JSON provides a format
that converts a server side structure into a JavaScript object that one can use practically right out of the
box.
For Example,
{
"employees":
St. Joseph’s College of Engineering MCA 79
MC5303 Web Programming Essentials 2018-19
[
{"firstName": "Arjun", "lastName": "Singh"},
{"firstName": "Sanjay", "lastName": "Verma"},
{"firstName": "Peter", "lastName": "Sharma"},
]
}
The employees object is an array of 3 employee records (object)
Array
Array elements are generally of a basic type (number, string, boolean, or null), however can also be a
nested array or object. Elements are comma-delimited and contained within brackets:
myArray = ["John Doe"'29,true,null]
myArray = [[], {}]
myArray[2] true
Array with Objects
This array contains comma-delimited objects which each contain multiple comma-delimited objects which
each contain multiple comma delimited key/value pairs. Objects within an array can be accessed using the
array name and index:
myArray =
[
{"name": "John Doe", "age": 29},
{" name": "Anna Smith", "age": 24"},
{" name": "peter Jones", "age": 39"},
]
myArray[0].name John Doe
//method of the object to be initialised
//This is called constructor chaining.
Rectangle.call(this, w, h);
OUTPUT:
Login: karups
Script Explanation
In above written script we have created an object Student using new operator. While creating the object we
have written a constructor to which the initializing values are passed as parameter. Then using the variable
this we can access the data properties of the object Student. Similarly the method display is initialized in
Std_III.display(). Hence as an output we can see the values that gets assigned to the data properties.
Thus we create a collection of objects using the same constructor then it resembles the concept of class in
the object oriented programming. But there is such class concept in javascript , although it supports the
concept of object. Hence javascript is called as object based programming.
Javascript provides a special predefined constructor function called Object(), used with the new keyword,
to bulid a genric object. The return value of the Object() constructor is assigned to a variable.
The variable contains a reference to an instance of a new object. Program below create a user-defined
function that will act as a constructor.
Syntax:
Var myobj = new Object();
For example
<html>
<head><title>The object() Constructor</title>
<script type = “text/javascript”>
Var cat = new Object();
Alert(cat);
</script>
<body>
</body>
</html>
Explanation
The Object() constructor creates and returns a reference to a cat object.
The returned value from the Object() constructor is a reference to an object.[object Object] means that the
cat is a descendant of the Object object from which all objects are derived.
Prototyping
In a language such as java or c++ , to create a class as an extension of another, one define the class in such
a way that it inherits the functionality of the higher-level object and overrides whatever functionality
ha/she does not want.
Javascript , on the other hand , provides for a constructor, via object, that allows one to create new onjects.
It is the object constructor that allocates the memory for the object , including all of its properties.
The Object also provides a prototype property that enables to extend nay object, including the built-in-
ones such as String and Number. One uses this prototype to derive new object methods and properties,
rather than class inheritance:
Number.prototype.add = function(val1,val2) {return val1+val2;}
Var num = new Number();
St. Joseph’s College of Engineering MCA 85
MC5303 Web Programming Essentials 2018-19
Num.prototype.add = function(val1,val2)
Var sum =num.add(8,3);//sum is 11
This demonstrates of the dynamic nature of Javascript, and how one can add new methods and properties
to objects at runtime. There is a difference between adding a new property or method to an instance of an
object and extending the object through prototype,
The following code is not the same as the preceding code snippet because the add method now applies only
to the object instance, and not to all instances of an object:
Var num = new Number();
Num.add=function(val1,val2){return val1+val2};
Var sum = num.add(8,3);
When anyone extent an object through prototype, the method or property is available to all instances of the
object. When he/she extend an object instance with a new property or method, it is available only to the
instance.
The concept of extending objects via prototyping is best explained through a demonstration.
The following example demonstrates how to extend the employee object by defining a new method, trim,
using the underlying object prototype property. Example
<!DOCTYPE html>
<html>
<body>
<script>
function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}
document.write(fred.salary);
</script>
</body>
</html>
20000
Java, c++ and other class-based object-oriented languages have an explicit concept of the class hierarchy.
Every class can have a superclass from which it inherits properties and methods. Any class can be
extended, or subclasses, so that the resulting sub class inherits its behavior.
Javascript supports inhertitance inststead of class-bases inheritance. Still javascript anologies to the class
hierarchy can be drawn.
In javavscript , the Object class is the most generic, and all other classes are specialized versions, or
subclasses, of it. Another way to say this is that object is the superclass of all built-in classes, and all
classes inherit in a few basic methods from object.
The classes are all direct subclasses of object. When necessary however, it is possible to subclass any other
class. For example
<script language="javascript" type="text/javascript">
<!--
// thanks to webreference
function superClass() {
this.supertest = superTest; //attach method superTest
}
St. Joseph’s College of Engineering MCA 86
MC5303 Web Programming Essentials 2018-19
function subClass() {
this.inheritFrom = superClass;
this.inheritFrom();
this.subtest = subTest; //attach method subTest
}
function superTest() {
return "superTest";
}
function subTest() {
return "subTest";
}
//-->
</script>
function superClass() {
this.supertest = superTest; //attach method superTest
}
function subClass() {
this.inheritFrom = superClass;
this.inheritFrom();
this.subtest = subTest; //attach method subTest
}
function superTest() {
return "superTest";
}
function subTest() {
return "subTest";
}
//-->
</script>
11) i) Explain any four jQuery AJAX methods in detail. (May 2015)
JQuery provides load() method to do the job −
Syntax
Here is the simple syntax for load() method −
URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP,
JSP, or PHP script which generates data dynamically or out of a database.
callback − A callback function invoked after the response data has been loaded into the elements
of the matched set. The first parameter passed to this function is the response text received from
the server and second parameter is the status code.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
</body>
</html>
Here load() initiates an Ajax request to the specified URL/jquery/result.html file. After loading this file,
all the content would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html
file has just one HTML line −
St. Joseph’s College of Engineering MCA 89
MC5303 Web Programming Essentials 2018-19
1 jQuery.ajax( options )
2 jQuery.ajaxSetup( options )
Setup global settings for AJAX requests.
8 serialize( )
Serializes a set of input elements into a string of data.
9 serializeArray( )
Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for
you to work with.
ii) With an example, illustrate how to convert a JSON Text to a JavaScript object.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var text = '{"employees":[' +
St. Joseph’s College of Engineering MCA 90
MC5303 Web Programming Essentials 2018-19
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
</body>
</html>
Create Object from JSON String
Anna Smith
console.log(diff);
Actual Return:
14) How to implement inheritance in JavaScript? Discuss with example. (May 2016)
A definition
If there was one thing common to all definitions of inheritance, it would probably be the
identification of a hierarchy between types (or objects in the case of JavaScript) that permits some
kind of delegation between members of said hierarchy.
Given this, how about:
Inheritance in JavaScript is the ability to have an object delegate some or all of its implementation
to another, by way of a hierarchical link.
JavaScript can be said to provide such a link natively via the prototype-chain (i.e. the chain of
[[Prototype]] references).
Inheritance over time
Prior to ES5, inheritance was achieved thus:
function Parent() {
this.foo = function() {
console.log('foo');
};
}
Parent.prototype.bar = function() {
console.log('bar');
}
function Child() {
}
Child.prototype = p = new Parent();
But, if you inspect the cat in Example C you get this result:
catC.__proto__;
Cat {age: 0}
even though they were not created using a constructor function. Since we didn't specify a prototype
for these, they have a prototype of Object. It is possible to create objects without a prototype using
this syntax: var myObject = Object.create(null);, but that is very rare and I've never seen a use for
it. So barring that example, I think it is safe to say that all objects eventually inherit from Object.
This is even true of catC; look what happens when we inspect catC further:
catC.__proto__;
Cat {age: 0}
catC.__proto__.__proto__;
Object { }
catC.__proto__.__proto__.__proto__;
null
Notice that catC has a prototype (__proto__) of Cat. Actually, to say it that way is not really
accurate. Cat is a function, so it cannot be a prototype; remember in the definitions above that a
prototype is not a function it is an object instance. This is important to remember when thinking
about prototypes -- an object's prototype is not the function that created it but an instance of an
object. Since this is important, let's explore it a bit further:
Cat;
function Cat(name, color) {
this.name = name;
this.color = color;
}
Cat.prototype;
Cat {age: 0}
catC;
Cat {name: "Fluffy", color: "White", age: 0}
Look at the difference between Cat, Cat.prototype and catC. What this is showing is that Cat is a
function but Cat.prototype and catC are objects. It further shows that Cat.prototype has an age
property (set to 0) and catC has three properties -- including age...sort of (stay tuned). When you
define a function, it creates more than just the function, it also creates a new object with that
function as it's type and assigns that new object to the function's prototype property. When we first
created the Cat function, before we executed the line Cat.prototype.age = 0;, if we would have
inspected Cat's prototype it would have looked like this: Cat {}, an object with no properties, but
of type Cat. It was only after we called Cat.prototype.age = 0;that it looked like this: Cat {age: 0}.
UNIT-V
1) Explain the setting up the environment for LAMP server.
PHP is a simple yet powerful language designed for creating HTML content. It describes the nature
and history of PHP , which platform it runs on;and how to download , install and configure it.
Seeting up the LAMP SERVER
The LAMP server(Linux, Apache, MYSQO, PHP(or perl)) is one of the most important servers one
might ever set up.
Since the LAMP server’s underlying foundation is Linux, it has rock-solid reliability, security and can
be installed on all kinds of hardware .
Here we installing the LAMP server on an Ubuntu 9.10 machine. This machine can be either a
standard installation or an Ubuntu Server installation. Either way, it is all command lines from here.
Because the OS is already installed, all we have to install is Apache, MYSQL and PHP. So there are
only three major steps to take care of in order to get the LAMP server up and running.
Apache
Apache is a web server. From within the terminal window type the command:
Sudo apt-get install apache2
If, by chance, you are using a distribution that does not use Sudo, you will need su to the root user and
issue the above command without the sudo command.
Depending on your OS installation , the above command might need to pick up some dependencies. If
so, those dependencies. At the end of the installation , apache should automatically start. If is does not ,
issue the following command
Sudo/etc/init.d/apache2 start
You can now open up a browser and point it to the IP address of the server to get the famous “It
works” page. You are ready to move on to PHP.
PHP
To begin the process of installing PHP, issue the following command
Sudo apt-get-install php5 libapache2-mod-php5
When the installation is complete, restart Apache with the command :
Sudo/etc/init.d/apache2 restart
Now, let us give PHP a little test to make sure it has installed. In the terminal window, create a new file
called test.php
Save that file place it in /var/www/. Now open up the browser to the address
http://ADDRESS_OF_SERVER/test.php and wgere ADDRESS_OF_SERVER is the actual address
of the server. You should see “test PHP pge” in the browser.
MYSQL
Mysql is the database piece of the puzzle. This installation requires a few more steps than what users
have just experienced. The first step is to install the server itself with the command
Sudo apt—get-install mysql-server
Again, depending upon the os installation, there might be some dependencies to be installed
After the installation is complete users need to log into the Mysql prompt and give the administrative
user a password. Do this by following steps:
Log into MYSQL with the command mysql-u root-p.
As no password has been configured, you will only need to hit enter when prompted for the password.
Enter the command SDEWT PAAWORD FOR ‘root’@’localhost’= PASSWORD(‘YOUR
PASSWORD’); Where YOURPASSWORD is the password you want to use for the administrative
user.
St. Joseph’s College of Engineering MCA 93
MC5303 Web Programming Essentials 2018-19
Now quit the MYSQL prompt by issuing the command quit and hitting enter.
Start the MYSQL server with the command sudo/etc/init.d/mysql start.
Now the LAMP SERVER IS NOW UP AND RUNNING. FROM THE TERMINAL WINDOW,
ISSUE THE COMMAND
Sudo tasksel
This command will open a curses-based tool which allows one to select numerous software options for
installation.
One of those selections is a LAMP server. All you need to do is mark LAMP server for installation.
Once you have selected LAMP server, hit the Tab key on the “button” and hit the Enter key. You will
have to answer a single question when you get to the MYSQL portion of the install.
Variables:
Variables are used for storing values, like text strings, numbers or arrays.
When a variable is declared, it can be used over and over again in your script.
All variables in PHP start with a $ sign symbol.
A variable should start with a letter or by the symbol(_)underscore.
Creation of a Variable:
The correct way of declaring a variable in PHP:
$var_name = value;
*Datatype is not specified during declaration.According to the assigned value the variable will
act as an integer,float or string.
Example:
<?php
$txt="Hello World!"; //Here the variable txt is of string datatype.
$x=16; //Here the variable x is of type integer.
$x1=16.2345; //Here the variable x1 is of float datatype.
?>
The following simple data types are supported by PHP
Integer: A whole number (no fractions), such as –43, 0, 1, 27, or 5438. The range of integers that is
allowed varies, depending on the operating system
Floating point number: A number (usually not a whole number) that includes decimal places,
such as 5.24 or 23.456789. This is often called a real number or a float.
Character string: A series of single characters, such as hello. There is no practical limit on the
length of a string.
Boolean: A TRUE or FALSE value. The string FALSE (can be upper- or lowercase), the integer
0, the float 0.0, an empty string and the constant NULL are considered FALSE. When Boolean
values are displayed FALSE displays as a blank string and TRUE echoes a 1.
Conversion of Data Types of variables
If there are two variables of different data types in an expression, PHP automatically
converts and promotes the data type of one variable to the data type of the other variable with
higher precision.
Example:
$firstNumber = 1; // PHP stores it as an integer
$secondNumber = 1.1; // PHP stores it as a float
$sum = $firstNumber + $secondNumber;
In the above piece of code, the data type of $firstnumber is automatically converted to
float by PHP. If a number is enclosed within a string, in arithmetic expressions, the string containing
numbers is automatically converted to a number.
Example:
$var1 = “1”;
$var2 = 2;
$total = $var1 + $var2;
Here, the value in $total is 3 because PHP automatically converts “1” to 1.
If a String is used in an arithmetic expression and it does not contain any number, then
PHP treats the string as number 0 in evaluating the expression.
The programmer also can change the way a variable is stored by using specific type cast.
The value in the variable on the right side of the equal sign is stored in the variable on the left
side as the specified type.
Example:
St. Joseph’s College of Engineering MCA 94
MC5303 Web Programming Essentials 2018-19
$intvar = 10;
$floatvar = 100.10;
$intvar = (int)$floatvar;
In the above example, the value in $floatvar is converted to integer and stored in $intvar.
After the type cast, $intvar contains the value 100.
Displaying the variable:
The value in a variable can be displayed using the echo statement.
The data type of a variable can be displayed using the var_dump function. To display the
data type of a variable $var we can use var_dump($var).
Removing Variables
The information in a variable can be removed setting the variable to an empty string. For
example setting $var = “” removes the information stored in the variable. If the variable $var is
displayed, nothing in echoed.
A variable can also be uncreated using the unset function. Passing a variable or variables
as parameter to the unset function uncreates the variable. Any further use of the variable will
give an undefined variable error.
Constants
Constants are similar to variables, that is they act as a placeholder for storing values. But
the value stored in a constant cannot change during the execution of the script.
Constant creation
Constants are created using the define statement. The format for creating a constant is
define(“constantname”,”constantvalue”);
Points to remember when using constants
The name of a constant does not begin with a $
We can store either a string or a number in a constant
By convention constant names are given in Capital letters but PHP accepts lowercase
letters also.
When using a constant in an expression, the double quotes must be removed.
Using a constant ensures that the value won’t be changed accidentally somewhere in the
script, leading to the wrong value being used in statements later in the script
Example
define (“INTEREST”, 10.2);
The following statement defines a constant named INTEREST and assigns to it the value
10.2. This constant can be used as $a=INTEREST *$b;
STRINGS:
Strings
A character string is a series of characters and characters are letters, numbers, and
punctuation. Character strings are stored in a variable by using double quotes(“) or single quotes (‘) which
mark the beginning and end of the string.
Special characters like \n (for newline) \t(for tab) can be used only within strings created
using double quotes. In single quoted strings special characters have no meaning and they are
output as any other character.
The difference between using single quotes and double quotes are as follows
Single-quoted strings are stored literally, with the exception of \’, which is stored as an apostrophe. \n
and \t are echoed literally. A variable $var inside a single quoted string is
displayed as $var itself and not by its value.
In double-quoted strings, variables and special characters are evaluated before the string
is stored. For example \n is treated as a newline and display moves to the next line when
echo is used $var inside a double quoted string is evaluated for its value.
Escaping characters within strings
Characters that tell PHP to remove the special meaning of certain characters in a string
and treat them as literals are called escaping characters. The special meaning of a character can
be removed by preceding it with a \.
Examples:
Preceding $ with \ removes its special meaning and the characters following $ are not
treated as variables. echo “\$var”; will output $var and not the value in $var.
Similarly \ and “ can also be escaped by using \ before them.
St. Joseph’s College of Engineering MCA 95
MC5303 Web Programming Essentials 2018-19
String Concatenation:
The process of joining strings is called as concatenation. Strings can be joined in PHP
using the .(dot) operator.
Example:
$a = “Hello”;
$b = “World”;
$c = $a.$b; // $c = HelloWorld
Inbuilt functions for String manipulations
1. trim($str), ltrim($str) and rtrim($str)
The trim functions are used for removing leading and/or trailing spaces in a string. trim()
removes both leading and trailing spaces, ltrim removes leading spaces and rtrim
removes trailing spaces.
2. str_word_count($str)
This functions returns the number of words in the string $str.
This function can also be invoked with one more parameter. If this function is called as
str_word_count($str,1), then the words in the string are returned as an array with the first
word at index 0.
3. str_repeat($str,$n)
This function repeats the string $str $n times and returns it as a string
4. str_replace($a,$b,$str)
This function replaces all occurrences of $a with $b in the string $str and returns the new
string.
5. strlen($str)
This function returns the length of the string $str.
6. strpos($str, $substr)
This function returns the position of first $substr beginning in $str.
7. strrev($str)
This function reverses the string and returns it.
8. strtolower($str)
This function returns the lowercase version of the string $str.
9. strtoupper($str)
This function returns the uppercase version of the string $str.
10. substr($str,$n1,$n2)
This function returns the substring from position $n1 for upto $n2 chracters in $str and
returns it.
11. strcmp($str1,$str2) and strcasecmp($str1,$str2)
Compares two strings on alphabetical and numerical order . Returns -1 if str1 is less, 0 if
two strings are equal, or +1 if str1 is greater. strcmp is casesensitive. strcasecmp is not.
Arrays
Arrays are complex variables that store a group of values under a single variable name.
An array is useful for storing a group of related values.
In PHP arrays are nothing but group of key/value associations under a single array name.
The keys can be either numeric or text. Depending on the type of key, the arrays are classified as
Numeric Arrays (Keys are numbers)
Associative Arrays (Keys are strings)
Creation of Arrays
Arrays can be created in the following ways
11.1.1.By specifying the key/value association for every element:
Example for creating numeric array:
$studname[1] = “Anil”;
$studname[2] = “Bheema”;
This creates an array called $studname with two elements and they can be accessed as
$studname[1] and $studname[2]. The key/value associations are 1/Anil and 2/Bheema.
Example for creating Associative array:
$state[‘TN’] = “Tamil Nadu”;
$state[‘KA’] = “Karnataka”;
$state[‘AP’] = “Andhra Pradesh”;
This creates an associative array with 3 elements.
By not giving any key for the array
An array can be created by not giving any specific key to the values. This automatically
St. Joseph’s College of Engineering MCA 96
MC5303 Web Programming Essentials 2018-19
creates an array that starts at key number 0.
Example:
$streets[] = “MG St.”;
$streets[] = “Renga St.”;
$streets[] = “Andar St.”;
This creates an array called $street with 3 elements and the first element can be located at
$streets[0].
By using the array function
Example for creating numeric array:
$vowels = array(‘a’,’e’,’i’,’o’,’u’);
This creates an array with 5 elements and the first element starts at index 0.
Example for creating associative array
$counCap = array("India" => "NewDelhi","China"=>"beijing");
This creates an associative array with 2 elements. The following key/value associations
are made
$counCap[“India”] = “NewDelhi”;
$counCap[“China”] = “Beijing”;
By specifying a range
An array with a range of values can be created by using the following statement:
$years = range(2001, 2010);
The resulting array looks like the following:
$years[0] = 2001
$years[1] = 2002
...
$years[8] = 2009
$years[9] = 2010
Appending an existing array
An existing array can be appended by not specifying the key for the new value to be
added. PHP automatically gives the next number as the key for both numeric and associative
arrays.
Example:
In the above $counCap array, the following entry can be made
$counCap[] = “Colombo”;
Here, “Colombo” gets added to the array and is automatically associated with the key 0.
Similarly, in the above $years array, the statement $years[] = 2011; associates 2011 to key 10.
Viewing Arrays
The structure and values of any array can be viewed by using one of two statements —
var_dump or print_r.
Example:
$customers= array(“Ram”,”Laksman”,”Sita”);
print_r($customers) will give the following output
(
[1] => Ram
[2] => Lakshman
[3] => Sita
)
Var_dump($customers) gives the following output
array(3) {
[1]=>
string(9) “Ram”
[2]=>
string(9) “Laksman”
[3]=>
string(10) “Sita”
}
Removing values from Arrays
A value can be removed from an array using the unset($arrname[key]) statement. An
array also can be completely removed using the unset($arrname) statement.
Using Arrays in echo
To display an array element $arrname[2], it can be used in echo as echo $arrname[2];
To display an array element value in an echo statement containing double quotes, then
St. Joseph’s College of Engineering MCA 97
MC5303 Web Programming Essentials 2018-19
the array element reference must be enclosed within curly braces as follows:
echo “The value of array element 2 is {$arrname[2]}”;
Handling arrays with loops:
Arrays and loops are natural combination –arrays are indexed using an array index,and
loops use a loop counter.By using the loop counter as the array index we can increment through
an entire array.
EX:
<?php
$actors[0]=”sathyam”;
$actors[1]=”sivam”;
$actors[2]=”sundaram”;
For($loop_index=0;$loop_index<count($actors);$loop_index++)
{
Echo “ $actors($loop_index)=”,$actors($loop_index),”<bre>”;
}
Here the count($actors) gives the no. of values stored in the array actor.i.e.,3.
From index 0 to 2 the values are extracted from the array .the output of the pgm is
$actors[0]=sathyam
$actors[1]=sivam
$actors[2]=sundaram
4) Explain the different types of operator in php with example program.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators:
There are following arithmetic operators supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
% Modulus Operator and remainder of after an B % A will give 0
integer division
++ Increment operator, increases integer value A++ will give 11
by one
-- Decrement operator, decreases integer value A-- will give 9
by one
<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b;
echo "Addtion Operation Result: $c <br/>";
$c = $a - $b;
echo "Substraction Operation Result: $c <br/>";
$c = $a * $b;
echo "Multiplication Operation Result: $c <br/>";
St. Joseph’s College of Engineering MCA 98
MC5303 Web Programming Essentials 2018-19
$c = $a / $b;
echo "Division Operation Result: $c <br/>";
$c = $a % $b;
echo "Modulus Operation Result: $c <br/>";
$c = $a++;
echo "Increment Operation Result: $c <br/>";
$c = $a--;
echo "Decrement Operation Result: $c <br/>";
?>
</body>
</html>
This will produce following result
Addtion Operation Result: 62
Substraction Operation Result: 22
Multiplication Operation Result: 840
Division Operation Result: 2.1
Modulus Operation Result: 2
Increment Operation Result: 42
Decrement Operation Result: 43
Comparison Operators:
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
== Checks if the value of two operands are equal (A == B) is not true.
or not, if yes then condition becomes true.
!= Checks if the value of two operands are equal (A != B) is true.
or not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less (A < B) is true.
than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.
<= Checks if the value of left operand is less (A <= B) is true.
than or equal to the value of right operand, if
yes then condition becomes true.
<html>
<head><title>Comparision Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
if( $a == $b ){
echo "TEST1 : a is equal to b<br/>";
}else{
echo "TEST1 : a is not equal to b<br/>";
}
if( $a > $b ){
echo "TEST2 : a is greater than b<br/>";
}else{
echo "TEST2 : a is not greater than b<br/>";
}
if( $a < $b ){
echo "TEST3 : a is less than b<br/>";
}else{
echo "TEST3 : a is not less than b<br/>";
}
if( $a != $b ){
echo "TEST4 : a is not equal to b<br/>";
}else{
echo "TEST4 : a is equal to b<br/>";
}
if( $a >= $b ){
echo "TEST5 : a is either grater than or equal to b<br/>";
}else{
echo "TEST5 : a is nieghter greater than nor equal to b<br/>";
}
if( $a <= $b ){
echo "TEST6 : a is either less than or equal to b<br/>";
}else{
echo "TEST6 : a is nieghter less than nor equal to b<br/>";
}
?>
</body>
</html>
This will produce following result
TEST1 : a is not equal to b
TEST2 : a is greater than b
TEST3 : a is not less than b
TEST4 : a is not equal to b
TEST5 : a is either grater than or equal to b
TEST6 : a is nieghter less than nor equal to b
Logical Operators:
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Operator Description Example
and Called Logical AND operator. If both the (A and B) is true.
operands are true then then condition
becomes true.
or Called Logical OR Operator. If any of the (A or B) is true.
two operands are non zero then then
condition becomes true.
&& Called Logical AND operator. If both the (A && B) is true.
operands are non zero then then condition
becomes true.
|| Called Logical OR Operator. If any of the (A || B) is true.
two operands are non zero then then
condition becomes true.
! Called Logical NOT Operator. Use to !(A && B) is false.
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.
<html>
<head><title>Logical Operators</title><head>
<body>
<?php
$a = 42;
$b = 0;
if( $a && $b ){
echo "TEST1 : Both a and b are true<br/>";
}else{
echo "TEST1 : Either a or b is false<br/>";
}
if( $a and $b ){
echo "TEST2 : Both a and b are true<br/>";
}else{
echo "TEST2 : Either a or b is false<br/>";
}
if( $a || $b ){
echo "TEST3 : Either a or b is true<br/>";
}else{
echo "TEST3 : Both a and b are false<br/>";
}
if( $a or $b ){
echo "TEST4 : Either a or b is true<br/>";
}else{
echo "TEST4 : Both a and b are false<br/>";
}
$a = 10;
$b = 20;
if( $a ){
echo "TEST5 : a is true <br/>";
}else{
echo "TEST5 : a is false<br/>";
}
if( $b ){
echo "TEST6 : b is true <br/>";
}else{
echo "TEST6 : b is false<br/>";
}
if( !$a ){
echo "TEST7 : a is true <br/>";
}else{
echo "TEST7 : a is false<br/>";
}
if( !$b ){
echo "TEST8 : b is true <br/>";
}else{
echo "TEST8 : b is false<br/>";
}
?>
</body>
</html>
This will produce following result
TEST1 : Either a or b is false
TEST2 : Either a or b is false
TEST3 : Either a or b is true
TEST4 : Either a or b is true
TEST5 : a is true
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false
Assignment Operators:
There are following assignment operators supported by PHP language:
Operator Description Example
= Simple assignment operator, Assigns C = A + B will assigne value of A + B into C
values from right side operands to left
side operand
+= Add AND assignment operator, It adds C += A is equivalent to C = C + A
right operand to the left operand and
assign the result to left operand
-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A
subtracts right operand from the left
operand and assign the result to left
operand
*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A
multiplies right operand with the left
operand and assign the result to left
operand
/= Divide AND assignment operator, It C /= A is equivalent to C = C / A
divides left operand with the right
operand and assign the result to left
operand
%= Modulus AND assignment operator, It C %= A is equivalent to C = C % A
takes modulus using two operands and
assign the result to left operand
<html>
<head><title>Assignment Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression for a true or false
value and then execute one of the two given statements depending upon the result of the evaluation. The
conditional operator has this syntax:
Operator Description Example
?: Conditional Expression If Condition is true ? Then value X : Otherwise
value Y
<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 10;
$b = 20;
Operators Categories:
All the operators we have discussed above can be categorised into following categories:
Unary prefix operators, which precede a single operand.
Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
The conditional operator (a ternary operator), which takes three operands and evaluates either the second
or third expression, depending on the evaluation of the first expression.
Assignment operators, which assign a value to a variable.
Precedence of PHP Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than +
so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Unary ! ++ -- Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if a condition is true and another code if the
condition is false
if...elseif....else statement - use this statement to select one of several blocks of code to be executed
switch statement - use this statement to select one of many blocks of code to be executed
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition) code to be executed if condition is true;
The following example will output "Have a nice weekend!" if the current day is Friday:
<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html>
Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition is true.
The if...else Statement
Use the if....else statement to execute some code if a condition is true and another code if a condition is
false.
Syntax
if (condition) code to be executed if condition is true; else code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will
output "Have a nice day!":
<html> <body>
<?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?>
</body> </html>
If more than one line should be executed if a condition is true/false, the lines should be enclosed within
curly braces:
<html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice weekend!";
echo "See you on Monday!"; } ?> </body> </html>
The if...elseif....else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is
true; else code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice
Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun")
echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html>
PHP Switch Statement
Conditional statements are used to perform different actions based on different conditions.
The PHP Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if
n=label2; break; default: code to be executed if n is different from both label1 and label2; }
St. Joseph’s College of Engineering MCA 104
MC5303 Web Programming Essentials 2018-19
This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from running
into the next case automatically. The default statement is used if no match is found.
Example
<html> <body> <?php $x=1; switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2";
break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html>
PHP Functions
The real power of PHP comes from its functions.
In PHP, there are more than 700 built-in functions.
PHP Functions
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName() { code to be executed; }
PHP function guidelines:
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)
Example
A simple function that writes my name when it is called:
<html> <body> <?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is ";
writeName(); ?> </body> </html>
Output:
My name is Kai Jim Refsnes
PHP Functions - Adding parameters
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:
<html> <body> <?php function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name
is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is
"; writeName("Stale"); ?> </body> </html>
Output:
My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes.
Example 2
The following function has two parameters:
<html> <body> <?php function writeName($fname,$punctuation) { echo $fname . " Refsnes" .
$punctuation . "<br />"; } echo "My name is "; writeName("Kai Jim","."); echo "My sister's name is ";
writeName("Hege","!"); echo "My brother's name is "; writeName("Ståle","?"); ?> </body> </html>
Output:
My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Ståle Refsnes?
PHP Functions - Return values
To let a function return a value, use the return statement.
Example
<html> <body> <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?
> </body> </html>
Output:
1 + 16 = 17
</body>
</html>
Further, we also learned how we could quickly output variables from PHP code without all of the hassle of
an echo statement by doing the following:
<?=$variable?>
Today, we will extend our knowledge of embedded PHP by discussing how PHP can be used to control the
flow of a web page through conditionals or repetition-control structures.
How it works
As mentioned in earlier articles, PHP will only process things that are enclosed within one of its valid code
blocks (such as <?phpand ?>). Because of this, PHP effectively ignores everything that it was not
specifically told to process and can be used to our advantage. For example, what will the output from the
following be?
<?php
$var = 5;
?>
<?=$var?><br />
Is this a valid script? Yes, the output would be the following:
$var = 10;
The variable $var has a value of: 5
Notice that with the second assignment of $var, when we attempt to change the value from 5 to 10, it has
no effect because it is not enclosed within valid PHP code-block syntax. So, instead of being processed, it
is simply displayed to the web browser.
Embedded conditionals
What if we wanted to display HTML only under specific conditions? For example, we only want PHP to
display a navigation menu if the user is validated -- how could we do this? Using what we already know,
we could simply put all the code for the HTML menu within echo statements (paying careful attention to
add a backslash any time we need to output a quote for our HTML to the web browser) but this method can
quickly become cumbersome and difficult to follow. Instead, to deal with situations like this, we will
introduce a new flavor of our code-block syntax:
<?php if(conditions) { ?>
... HTML CODE ...
<?php } ?>
Although this may be confusing, remember how PHP will process this code. To start, it will evaluate the
first line of a normal ifstatement and then begin a code block. Then, we turn off PHP parser and jump into
normal HTML code (all of which PHP will simply output to the browser and ignore) until, finally, we
return to PHP code and close our if statement. The result of this technique is a way for us to control regular
and standard HTML with nearly no intrusion by PHP into the syntax. Although the above example works,
<?php
$myacno= $_POST['acc_no'];
$mytitle = $_POST['tit'];
$myauth = $_POST['author'];
$myedition = $_POST['edition'];
if (empty($myacno) || empty($mytitle) || empty($myauth) || empty($myedition))
{
echo "<script>alert('Empty fields not allowed')</script>";
echo "<script>location.href='admin.php'</script>";
die();
}
$con=mysql_connect('localhost','root','','');
mysql_select_db("csv_db",$con);
$result= mysql_query("select * from table1 where (edition='$myedition' && tit ='$mytitle' &&
author='$myauth') || (accno='$myacno')");
$rows=mysql_num_rows($result);
if ($rows>=1)
{
St. Joseph’s College of Engineering MCA 109
MC5303 Web Programming Essentials 2018-19
echo "Book Id or Bood is already exist";
header("Location:admin.php");
die();
}
mysql_query("insert into table1
(accno,tit,author,edition)VALUES('$myacno','$mytitle','$myauth','$myedition')");
echo "<script>alert('Record Added')</script>";
header("Location:admin.php");
?>
SEARCH CODE
<html><body>
<center>
<a href="admin.php"><img src="home.png"></a>
<a href="view.php"><img src="view.png"></a>
<form method = "post" action = "bs.php">
<div style = 'top: 200; left: 560; position: absolute; z-index:1;'>
<input type="text" name = "wala" value="name of book..." onblur="if (this.value == '') { this.value=
'name of book...'; }" onfocus="if (this.value == 'name of book...') { this.value= ''; }"/>
<button name = "search" style="background-color:transparent;"><img src="search2.png" alt="" onclick
= ''/> Search</button>
</div>
</form>
</BODY>
</HTML>
EDIT CODE
<?php
$mykey1=$_REQUEST['key1'];
$mykey2=$_REQUEST['key2'];
$mykey3=$_REQUEST['key3'];
$mykey4=$_REQUEST['key4'];
echo "<form action='update.php?key1=" . $mykey1 . "'method='POST'>";
ECHO "<CENTER>EDIT-INFORMATION</CENTER>";
echo "<center><table>";
echo "<TR><TD>Accn No</TD><TD><INPUT TYPE=text name='accno'
value=$mykey1></TD></TR>";
echo "<TR><TD>Title</TD><TD><INPUT TYPE=text name='tit' value=$mykey2 ></TD></TR>";
echo "<TR><TD>Author_Name</TD><TD><INPUT TYPE=text name='author' value=$mykey3
></TD></TR>";
echo "<TR><TD>Edition</TD><TD><INPUT TYPE=text name='edition'
value=$mykey4></TD></TR>";
echo "<TR><TD><INPUT TYPE=submit value=UPDATE></TD><TD><INPUT TYPE=reset
value='cancel'></TD></TR></table>";
?>
Output:
LOGIN PAGE
SEARCHING BOOK
BOOK BORROW-in this form by clicking borrow u get a confirmation msg that u borrowed by linking to
other page and db also will be updated that the book as borrowed
html>
<body>
<title>Factorial Program in PHP</title>
<!-- form post method -->
<form action="" method="post">
<label>Enter Number to calculate Factorial</label> <input type="text" name="number"
size="2" />
</form>
</body>
</html>
<?php
//check for post value if there then allow inside
if($_POST){
$fact = 1;
10) How to read from a web page? Explain with example.(May 2016)
Logic:
o Initializing first and second number as 0 and 1.
o Print first and second number.
o From next number, start your loop. So third number will be the sum of the first two numbers.
Fibonacci series using Recursive function
Recursion is a phenomenon in which the recursion function calls itself until the base condition is
reached.
<?php
/* Print fiboancci series upto 12 elements. */
$num = 12;
echo "<h3>Fibonacci series using recursive function:</h3>";
echo "\n";
/* Recursive function for fibonacci series. */
function series($num){
if($num == 0){
return 0;
}else if( $num == 1){
return 1;
} else {
return (series($num-1) + series($num-2));
}
}
St. Joseph’s College of Engineering MCA 113
MC5303 Web Programming Essentials 2018-19
/* Call Function. */
for ($i = 0; $i < $num; $i++){
echo series($i);
echo "\n";
}
ii) Create a form for student information. Write JavaScript code to find Total, Average,Result &Grade.
Refer the question no.9.
12) (i) Write a JavaScript to check whether a given number is prime or not.(May 2016)
Prime number in PHP
Example:
<?php
$count = 0;
$num = 2;
while ($count < 15 )
{
$div_count=0;
for ( $i=1; $i<=$num; $i++)
{
if (($num%$i)==0)
{
$div_count++;
}
}
if ($div_count<3)
{
echo $num." , ";
$count=$count+1;
}
$num=$num+1;
}
?>
Output:
Prime Number using Form in PHP
Example:
We'll show a form, which will check whether a number is prime or not.
<form method="post">
Enter a Number: <input type="text" name="input"><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if($_POST)
{
(ii) Write a HTML code to develop a website for University. Provide the links to department,
Examinations and Results with the use of suitable tags.
Refer previous answers