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

Mod 3

The document discusses JavaScript and its uses. It covers what JavaScript is, where it is used, its advantages and disadvantages. JavaScript is an object-oriented, dynamically typed scripting language that runs in web browsers. It is used to program interactive effects and dynamic content on web pages. The document also discusses other client-side technologies like Flash and Java applets and how they differ from JavaScript. Finally, it covers JavaScript design principles and how websites are developed in layered approaches with HTML, CSS, and JavaScript layers.

Uploaded by

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

Mod 3

The document discusses JavaScript and its uses. It covers what JavaScript is, where it is used, its advantages and disadvantages. JavaScript is an object-oriented, dynamically typed scripting language that runs in web browsers. It is used to program interactive effects and dynamic content on web pages. The document also discusses other client-side technologies like Flash and Java applets and how they differ from JavaScript. Finally, it covers JavaScript design principles and how websites are developed in layered approaches with HTML, CSS, and JavaScript layers.

Uploaded by

Sneha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 142

Module 3:

JavaScript: Client-Side Scripting

5/27/2022 Mrs. karthiga g 18cs63 1


CONTENTS

✔What is JavaScript and What can it do?


✔JavaScript Design Principles
✔Where does JavaScript Go?
✔Syntax
✔JavaScript Objects
✔The Document Object Model (DOM)
✔JavaScript Events
✔Forms
✔Introduction to Server-Side Development with PHP
✔What is Server-Side Development
✔A Web Server’s Responsibilities
✔Quick Tour of PHP
✔Program Control
✔Functions
5/27/2022 Mrs. karthiga g 18cs63 2
WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

✔JavaScript is an object-oriented, dynamically typed, client-side


scripting language.

✔It is the programming language of the Web.

✔Although it contains the word Java, JavaScript and Java are vastly
different programming languages with different uses.

✔Java is a full-fledged compiled, object oriented language, popular for


its ability to run on any platform with a Java Virtual Machine installed.

✔Conversely, JavaScript is one of the world’s most popular languages,


with fewer of the object-oriented features of Java, and runs directly
inside the browser, without the need for the JVM.
5/27/2022 Mrs. karthiga g 18cs63 3
WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

✔JavaScript is object oriented in that, almost everything in the


language is an object.

✔For instance, JavaScript variables are objects in that they have


constructors, properties, and methods.

✔Unlike more familiar object oriented languages such as Java, C#, and
Visual Basic, functions in JavaScript are also objects.

✔JavaScript is Dynamically Typed, also called Weakly Typed.

✔This means variables can be easily converted from one data type to
another.

5/27/2022 Mrs. karthiga g 18cs63 4


WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

There are 3 languages all web developers must learn:


HTML to define the content of web pages.
CSS to specify the layout of web pages.
JavaScript to program the behaviour of web pages.
Client-Side Scripting
✔This refers to the client machine (i.e., the browser) running code locally
rather than relying on the server to execute code and return the result.

✔JavaScript is one such client side scripting language that can operate on
most web browsers.

✔We will next see how a client downloads and executes a JavaScript.

5/27/2022 Mrs. karthiga g 18cs63 5


WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

Downloading and executing a client-side JavaScript script


5/27/2022 Mrs. karthiga g 18cs63 6
WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

Advantages of client side scripting


✔Processing can be offloaded from the server to client machines, thereby
reducing the load on the server.

✔The browser can respond more rapidly to user events than a request to a
remote server ever could, which improves the user experience.

✔Client side scripting provide Interoperability. For example, JavaScript can be


inserted into any web page. JavaScript can be used in many different kinds of
applications because of support in other languages like Pearl and PHP.

✔Client side scripting also gives developers more control over the look and
behaviour of their web pages. Features like drag and drop and sliders can be
added to the web page, which greatly enhances the user interface and
experience of a site.

5/27/2022 Mrs. karthiga g 18cs63 7


WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

Disadvantages of client side scripting

✔Not all browsers support scripts, therefore, users might experience


errors if no alternatives have been provided.

✔Different browsers and browser versions support scripts differently,


thus more quality assurance testing is required. What works in one
browser, may generate an error in another.

✔More development time and effort might be required (if the scripts
are not already available through other resources).

✔JavaScript-heavy web applications can be complicated to debug and


maintain.
5/27/2022 Mrs. karthiga g 18cs63 8
WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

✔Despite these limitations, the ability to enhance the visual appearance of a


web application while potentially reducing the demands on the server make
client-side scripting a powerful tool for a web developer.

✔Before going to the details of JavaScript, we will briefly look at two other
noteworthy client-side approaches to web programming.

✔The first approach is Adobe Flash.

✔Adobe Flash is a vector based drawing and animation program, a video file
format, and a software platform that has its own JavaScript-like
programming language called ActionScript.

✔Flash is often used for animated advertisements and online games, and can
also be used to construct web interfaces.

5/27/2022 Mrs. karthiga g 18cs63 9


WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

✔We will now see how flash works in the browser.

✔Flash objects are in a format called SWF (Shockwave Flash) and are included
within an HTML document via the <object> tag.

✔The SWF file is then downloaded by the browser and then the browser
delegates control to a plug-in to execute the Flash file.

✔A Browser Plug-in is a software add-on that extends the functionality and


capabilities of the browser by allowing it to view and process different types of
web content.

✔It should be noted that a browser plug-in is different than a Browser


Extension. Extensions extend the functionality of a browser but are not used
to process downloaded content.

5/27/2022 Mrs. karthiga g 18cs63 10


WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

Working of
Adobe Flash

5/27/2022 Mrs. karthiga g 18cs63 11


WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

✔The second (and oldest) of these alternatives to JavaScript is Java


applets.

✔An Applet is a term that refers to a small application that performs a


relatively small task.

✔Java applets are written using the Java programming language and are
separate objects that are included within an HTML document via the
<applet> tag.

✔These applets are downloaded and then passed on to a Java plug-in.

✔This plug-in then passes on the execution of the applet outside the
browser to the Java Runtime Environment (JRE) that is installed on
the client’s machine.
5/27/2022 Mrs. karthiga g 18cs63 12
WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

Working of Java
Applet

5/27/2022 Mrs. karthiga g 18cs63 13


WHAT IS JAVASCRIPT AND WHAT CAN IT DO?

✔Both Flash plug-ins and Java applets are losing support by


major players for a number of reasons.

✔First, Java applets require the JVM be installed and up to date.

✔Second, Flash and Java applets also require frequent updates,


which can annoy the user.

✔With the universal adoption of JavaScript and HTML5,


JavaScript remains the most dynamic and important client-side
scripting language for the modern web developer.

5/27/2022 Mrs. karthiga g 18cs63 14


JAVASCRIPT DESIGN PRINCIPLES

JavaScript Design Principles


Layers
✔Here we will look at the conceptual JavaScript layers.

✔Before that, we will first see how a website is developed in a layered


approach.

✔The key to accommodating the broadest possible range of visitors to


your site is to think of the Web in terms of three layers.

✔The layers correspond to the three kinds of code that are used in
building a website: HTML, CSS and JavaScript.

✔The three Layers of the Web are pictorially presented next.

7/6/2021 Mrs. karthiga g 18cs63 15


JAVASCRIPT DESIGN PRINCIPLES

✔We start by producing


the content in HTML format. This
is the base layer, which any visitor
using any kind of browser should be
able to view.

✔With that done, we can focus on


making the site look better, by
adding a layer
of presentation information using
CSS.

✔Lastly, we can use JavaScript to


introduce an added layer of
interactivity and dynamic behavior,
which will make the site easier to
The three layers of the Web use in browsers.

7/6/2021 Mrs. karthiga g 18cs63 16


JAVASCRIPT DESIGN PRINCIPLES

Further, the JavaScript layer


has its own set of layers.

Presentation Layer
✔Focuses on the display of
information.
✔JavaScript can alter the HTML
of a page, which results in a
change, visible to the user.
✔This includes common things
like creating, hiding, and
showing divs, using tabs to
show multiple views etc.
JavaScript Layers

7/6/2021 Mrs. karthiga g 18cs63 17


JAVASCRIPT DESIGN PRINCIPLES

Validation Layer
✔JavaScript can be also used to validate logical aspects of the user’s
experience.
✔This could include, for example, validating a form to make sure the
email entered is valid before sending it along.
✔The main intention of this layer is to pre validate forms before making
transmissions back to the server.

Asynchronous Layers
✔Normally, JavaScript operates in a Synchronous manner.
✔In this approach, a request sent to the server requires a response before
the next lines of code can be executed.
✔During the wait between request and response, the browser sits in a
loading state.
7/6/2021 Mrs. karthiga g 18cs63 18
JAVASCRIPT DESIGN PRINCIPLES

✔In contrast, an Asynchronous layer can route requests to the server in


the background.

✔In this model, as certain events are triggered, the JavaScript sends the
HTTP requests to the server.

✔However, while waiting for the response, the rest of the application
functions normally, and the browser isn’t in a loading state.

✔When the response arrives, JavaScript will make the necessary


updates in the page.

✔Let us take a simple JavaScript example to understand the difference


between Synchronous and Asynchronous approaches.

7/6/2021 Mrs. karthiga g 18cs63 19


JAVASCRIPT DESIGN PRINCIPLES

let a = 1
let b = 2
console.log(‘Synchronous’)
console.log(a)
console.log(b)
Synchronous
JavaScript
The above script is a simple synchronous JavaScript.

This means, the above script will execute in a sequence. The output of the
script would be,
Synchronous
1
2
✔ We now introduce some asynchronous features into the script.

7/6/2021 Mrs. karthiga g 18cs63 20


JAVASCRIPT DESIGN PRINCIPLES

let a = 1
let b = 2 Synchronous
setTimeout( function() { 1
console.log(‘Asynchronous’) 2
}, 1000) Asynchronous
console.log(‘Synchronous’)
console.log(a)
console.log(b)
Asynchronous Javascript
✔The above script is asynchronous and does not execute in a sequence.

✔We make the above script asynchronous by introducing an asynchronous function in it.

✔The asynchronous function introduced is setTimeout().

7/6/2021 Mrs. karthiga g 18cs63 21


JAVASCRIPT DESIGN PRINCIPLES

Users without JavaScript


✔In this section, we have a look at some clients that do not use java
scripts.

Web crawler
✔A Web crawler, sometimes called a spider or spiderbot, is an internet
bot that systematically browses the World Wide Web, typically for the
purpose of Web indexing.

✔A Crawler runs on behalf of a search engine(ex: Googlebot for


Google) to download your site, so that it can eventually be featured in
their search results.

✔These automated software agents do not interpret JavaScript.


7/6/2021 Mrs. karthiga g 18cs63 22
JAVASCRIPT DESIGN PRINCIPLES

Browser plug-in
✔There are many uses of JavaScript that are not desirable to the end
user.

✔Many malicious sites use JavaScript to compromise a user’s computer,


and many ad networks deploy advertisements using JavaScript.

✔This motivates some users to install plug-ins that stop JavaScript


execution(ex: ad-blocking plug-ins).

✔A browser plug-in is a piece of software that works within the browser,


that might interfere with JavaScript.

7/6/2021 Mrs. karthiga g 18cs63 23


JAVASCRIPT DESIGN PRINCIPLES

Text-based client
✔Some clients use a text-based browser.

✔A text-based web browser (ex: Lynx) is a web browser that renders


only the text of web pages, and ignores graphic content.

✔Text-based browsers are widely deployed on web servers, which are


often accessed using a command-line interface.

✔For such clients, JavaScript has no role to play as there is no graphical


interface.

✔A website administrator might want to see what an HTTP GET


request to another server is returning for testing or support purposes.
7/6/2021 Mrs. karthiga g 18cs63 24
JAVASCRIPT DESIGN PRINCIPLES

Visually disabled client

✔A visually disabled client will use special web browsing software to


read the contents of a web page out loud to them.

✔These specialized browsers do not interpret JavaScript, and some


JavaScript on sites is not accessible to these users.

✔Designing for these users requires some extra considerations, with


lack of JavaScript being only one of them.

✔WebbIE is a freely available text-only web browser for the visually


impaired.

7/6/2021 Mrs. karthiga g 18cs63 25


JAVASCRIPT DESIGN PRINCIPLES

The <noScript> Tag

✔The <noscript> tag defines an alternate content to be displayed to users that


have disabled scripts in their browser or have a browser that doesn't support
script.

✔Any text between the opening and closing tags will only be displayed to
users without the ability to load JavaScript.

✔It is often used to prompt users to enable JavaScript, but can also be used to
show additional text to search engines.
<script>
document.write("Hello World!")
</script>
<noscript>Your browser does not support JavaScript!</noscript>

7/6/2021 Mrs. karthiga g 18cs63 26


JAVASCRIPT DESIGN PRINCIPLES

✔With all this discussion, we can conclude that we should create


websites with all the basic functionality enabled using regular
HTML.

✔For those (majority) of users with JavaScript enabled, we can then


enhance the basic layout using JavaScript to:

Embellish the look of certain elements.


Animate certain user interactions.
Prevalidate forms.
Replace static HTML elements with more visually and logically
enhanced elements from JavaScript.

7/6/2021 Mrs. karthiga g 18cs63 27


JAVASCRIPT DESIGN PRINCIPLES

Graceful Degradation and Progressive


Enhancement
✔Over the years, browser support for different JavaScript objects has
varied.

✔Something that works in the current version of Chrome might not


work in IE version 8, something that works in a desktop browser
might not work in a mobile browser.

✔To tackle such scenarios, we consider two strategies web application


developers:
Graceful Degradation
Progressive Enhancement

7/6/2021 Mrs. karthiga g 18cs63 28


JAVASCRIPT DESIGN PRINCIPLES

Graceful Degradation

✔With this strategy we develop our site for the abilities of current
browsers.

✔For those users who are not using current browsers, we might provide
an alternate site or pages for those using older browsers that lack the
JavaScript (or CSS or HTML5) used on the main site.

✔The idea here is that the site is “degraded” (i.e., loses capability)
“gracefully”.

✔Graceful degradation is illustrated in the following figure.

7/6/2021 Mrs. karthiga g 18cs63 29


JAVASCRIPT DESIGN PRINCIPLES

Example of graceful degradation

7/6/2021 Mrs. karthiga g 18cs63 30


JAVASCRIPT DESIGN PRINCIPLES

Progressive Enhancement

✔This strategy takes the opposite approach to the problem.

✔In this case, the developer creates the site using CSS, JavaScript, and
HTML features that are supported by all browsers of a certain age or
newer.

✔To that baseline site, the developers can now “progressively” (i.e., for
each browser) “enhance” (i.e., add functionality) to their site based on
the capabilities of the users’ browsers.

✔This strategy is illustrated in the following figure.

7/6/2021 Mrs. karthiga g 18cs63 31


JAVASCRIPT DESIGN PRINCIPLES

Example of progressive enhancement

7/6/2021 Mrs. karthiga g 18cs63 32


JAVASCRIPT DESIGN PRINCIPLES

7/6/2021 Mrs. karthiga g 18cs63 33


WHERE DOES JAVASCRIPT GO?

Where Does JavaScript Go?


✔JavaScript can be linked to an HTML page in a number of ways.

✔Just as CSS styles can be inline, embedded, or external, JavaScript can be


included in a number of ways.

Inline JavaScript
Inline JavaScript refers to the practice of including JavaScript code directly
within certain HTML attributes. For example,

<input type="button” onclick="alert('Are you sure?');" />

✔Like CSS, Inline JavaScript is a bad practice and should be avoided.

✔Inline JavaScript is a real maintenance nightmare, requiring maintainers to scan


through almost every line of HTML looking for your inline JavaScript.

5/27/2022 Mrs. karthiga g 18cs63 34


WHERE DOES JAVASCRIPT GO?

Embedded JavaScript
Embedded JavaScript refers to the practice of placing JavaScript code within a
<script> element.
<html>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>
5/27/2022 Mrs. karthiga g 18cs63 35
WHERE DOES JAVASCRIPT GO?

External JavaScript
✔It is always a good practice to separate HTML and JavaScript.

✔JavaScript supports this separation by allowing links to an external file that contains
the JavaScript.

✔By convention, JavaScript external files have the extension .js

<head>
<script type="text/JavaScript" src="greeting.js">
</script>
</head>

These external JavaScript files typically contain function definitions, data


definitions, and other blocks of JavaScript code.

5/27/2022 Mrs. karthiga g 18cs63 36


SYNTAX

We start by having a look at some rules that must be followed while writing a
JavaScript.
✔Everything is type sensitive, including function, class, and variable names.

✔The scope of variables in blocks is not supported. This means variables


declared inside a loop may be accessible outside of the loop, counter to what
one would expect.

✔There is a === operator, which tests not only for equality but type
equivalence.

✔Null and undefined are two distinctly different states for a variable.

✔Semicolons are not required, but are permitted (and encouraged).

✔There is no integer type, only number.


5/27/2022 Mrs. karthiga g 18cs63 37
SYNTAX

Variables
✔Variables in JavaScript are dynamically typed, meaning a variable can be an
integer, and then later a string, then later an object.

✔Hence we do not require the familiar types like int, char, and String for variable
declaration.

✔Instead, to declare a variable x, we use the var keyword, the name, and a
semicolon.
var x;

Values can be assigned to the variables either at the time of declaration or run
time.
var y = 0; // y is defined and initialized to 0
y = 4; //y is assigned the value of 4

5/27/2022 Mrs. karthiga g 18cs63 38


SYNTAX

Comparison Operators

5/27/2022 Mrs. karthiga g 18cs63 39


SYNTAX

Logical Operators
✔JavaScript includes Boolean operators, which allow us to build complicated
expressions.

✔The Boolean operators and, or, and not and their truth tables are listed below.

5/27/2022 Mrs. karthiga g 18cs63 40


SYNTAX

Conditional Operators
✔JavaScript’s syntax is almost identical to that of Java, or C when it comes to
conditional structures such as if and if else.

✔In this syntax the condition to test is contained within ( ) brackets with the body
contained in { } blocks.

5/27/2022 Mrs. karthiga g 18cs63 41


SYNTAX

Loops
Like conditionals, loops use the ( ) and { } blocks to define the
condition and the body of the loop.

While Loops
The most basic loop is the while loop, which loops until the
condition is not met.
var i = 0;
while(i < 10){
//do something with i
i++;
}

5/27/2022 Mrs. karthiga g 18cs63 42


SYNTAX

For Loops
This statement begins with the for keyword and has the components placed
between ( ) brackets, semicolon (;) separated.
for (var i = 0; i < 10; i++){
//do something with i
}

Functions
Functions are the building block for modular code in JavaScript.

They are defined by using the reserved word function and then the function
name and (optional) parameters.

Since JavaScript is dynamically typed, functions do not require a return


type, nor do the parameters require type.

5/27/2022 Mrs. karthiga g 18cs63 43


SYNTAX

A function to raise x to the yth power is presented below,


function power(x,y){
var pow=1;
for ( var i=0; i<y ; i++ ){
pow = pow*x;
}
return pow;
}

The above function is called as power(2,10).

Alert
The alert() function makes the browser show a pop-up to the user, with
whatever is passed being the message displayed.

5/27/2022 Mrs. karthiga g 18cs63 44


SYNTAX

✔The pop-up may appear different to each user depending on their browser
configuration.

✔This pop-up obscures the underlying web page, and no actions can be done
until the pop-up is dismissed.
alert ( "Good Morning" );

Errors Using Try and Catch


✔When the browser’s JavaScript engine encounters an error, it will throw an
exception.

✔These exceptions interrupt the regular, sequential execution of the program


and can stop the JavaScript engine altogether.

5/27/2022 Mrs. karthiga g 18cs63 45


SYNTAX

However, we can optionally catch these errors preventing disruption of the program
using the try–catch block.

try {
nonexistantfunction("hello");
}
catch(err) {
alert("An exception was caught:" + err);
}

Throwing Your Own Exceptions


✔Although try-catch can be used exclusively to catch built-in JavaScript
errors, it can also be used by our programs, to throw our own messages.

✔The throw keyword stops normal sequential execution, just like the
built-in exceptions.

5/27/2022 Mrs. karthiga g 18cs63 46


SYNTAX

try {
var x = -1;
if (x<0)
throw "smallerthan0Error";
}
catch(err){
alert (err + "was thrown");
}
✔It should be noted that throwing an exception disrupts the sequential execution of a
program.

✔That is, when the exception is thrown all subsequent code is not executed until the
catch statement is reached.

✔Hence, try-catch and throw statements should be used for abnormal or exceptional
cases in your program. They should not be used as a normal way of controlling
flow.
5/27/2022 Mrs. karthiga g 18cs63 47
JAVASCRIPT OBJECTS

❖JavaScript objects can have constructors, properties, and methods


associated with them, and are used very much like objects in other
object-oriented languages.

❖There are objects that are included in the JavaScript language, we


can also define our own kind of objects.

Constructors
Normally to create a new object we use the new keyword followed
by the class name, and ( ) brackets with n optional parameters
inside, separated by comma as follows:

var someObject = new ObjectName(param 1,...., param n);

5/27/2022 Mrs. karthiga g 18cs63 48


JAVASCRIPT OBJECTS

✔For some classes, shortcut constructors are defined.

✔For example, a String object can be defined with the shortcut,


var greeting = "Good Morning";
✔Instead of the formal definition,
var greeting = new String("Good Morning");

Properties
✔Each object might have several properties defined.

✔A property can be accessed using dot notation where a dot between the
object name and the property references that property.
alert(someObject.property);

5/27/2022 Mrs. karthiga g 18cs63 49


JAVASCRIPT OBJECTS

Methods

✔Objects can also have methods, which are functions associated with an
instance of an object.

✔These methods are called using the same dot notation as for properties,
but instead of accessing a variable, we are calling a method.
someObject.doSomething();

Objects Included in JavaScript


✔Some of the prominent objects that are included in JavaScript are
Array, Boolean, Date, Math, String, and others.

5/27/2022 Mrs. karthiga g 18cs63 50


JAVASCRIPT OBJECTS

Arrays
✔Array objects can be created using the new syntax and calling the
object constructor.
var greetings = new Array();

✔The above code creates a new, empty array named greetings.

✔To initialize the array with values, the variable declaration would
look like the following:
var greetings = new Array("Good Morning", "Good noon");
or
var greetings = ["Good Morning", "Good noon"];

5/27/2022 Mrs. karthiga g 18cs63 51


JAVASCRIPT OBJECTS

Accessing and Traversing an Array


To access an element in the array we use the familiar square bracket
notation, with the index we wish to access inside the brackets.
for (var i = 0; i < greetings.length; i++){
alert(greetings[i]);
}

JavaScript array with indexes and values illustrated


5/27/2022 Mrs. karthiga g 18cs63 52
JAVASCRIPT OBJECTS

Modifying an Array
We now look at some functions associated with the array object.

To add an item to an existing array, we use the push method.


greetings.push("Good Evening");

The pop method removes an item from the back of an array.

Additional methods that modify arrays include:


concat() - creates a new array by merging (concatenating) existing
arrays.
reverse() – reverses the array elements.
shift() - removes the first array element and "shifts" all other elements
to a lower index.
sort() – sorts the elements of the given array.
join() - joins all array elements into a string.
5/27/2022 Mrs. karthiga g 18cs63 53
JAVASCRIPT OBJECTS

Math
✔The Math class allows one to access common mathematic functions and
common values quickly in one place.

✔This static class contains methods such as max(), min(), pow(), sqrt() and
exp().

✔Trigonometric functions such as sin(), cos() and arctan() are also provided
by the Math class.

✔In addition, many mathematical constants are defined such as PI, E(Euler’s
number).
Math.PI // 3.141592657
Math.sqrt(4); // square root of 4 is 2.
Math.random(); // random number between 0 and 1

5/27/2022 Mrs. karthiga g 18cs63 54


JAVASCRIPT OBJECTS

String
✔The String class provides facilities to create and concatenate strings.
var greet = new String("Good"); // long form constructor
var greet = "Good"; // shortcut constructor

✔To get the length of a string, the length property is used.


alert (greet.length);

✔Strings can be concatenated as shown below.


var str = greet.concat("Morning"); // Long form concatenation
var str = greet + "Morning"; // + operator concatenation

✔ Some more functions supported by the String class are charAt(),


indexOf(), split(), search(), match().

5/27/2022 Mrs. karthiga g 18cs63 55


JAVASCRIPT OBJECTS

Date
The Date class allows us to quickly calculate the current date or create
date objects for particular dates.

To display today’s date as a string, we would simply create a new


object and use the toString() method.
var d = new Date();
alert ("Today is "+ d.toString());

5/27/2022 Mrs. karthiga g 18cs63 56


THE DOCUMENT OBJECT MODEL

✔JavaScript is used to interact with the HTML document in which it is


contained.

✔For this, there needs to be some way of programmatically accessing


the elements and attributes within the HTML.

✔This is accomplished through a programming interface (API) called


the Document Object Model (DOM).

✔W3C defines DOM as,


“DOM is a Platform and language-neutral interface that will
allow programs and scripts to dynamically access and update the
content, structure and style of documents.”

5/27/2022 Mrs. karthiga g 18cs63 57


THE DOCUMENT OBJECT MODEL

For a given HTML document, we know that there is a corresponding


tree representation that presents the hierarchy of various elements.

5/27/2022 Mrs. karthiga g 18cs63 58


THE DOCUMENT OBJECT MODEL

✔This tree structure is formally called the DOM Tree with the root, or
topmost object called the Document Root.

Nodes
✔In the DOM, each
element within the HTML
document is called a
node.

✔There are element nodes,


text nodes and attribute
nodes.

5/27/2022 Mrs. karthiga g 18cs63 59


THE DOCUMENT OBJECT MODEL

✔All nodes in the DOM share a common set of properties and methods.

✔These properties and methods give some details about the nodes.

5/27/2022 Mrs. karthiga g 18cs63 60


THE DOCUMENT OBJECT MODEL

Document Object
✔The DOM document object is the root JavaScript object
representing the entire HTML document.

✔This object is accessed using the document keyword.

✔The attributes of this object include some information about the


page including doctype and inputEncoding.

✔These attributes are accessed as follows,


// specify the doctype, for example html
var a = document.doctype.name;
// specify the page encoding, for example ISO-8859-1
var b = document.inputEncoding;
5/27/2022 Mrs. karthiga g 18cs63 61
THE DOCUMENT OBJECT MODEL

In addition to these properties, there are some essential methods associated


with the document object.

Document Object Methods

5/27/2022 Mrs. karthiga g 18cs63 62


THE DOCUMENT OBJECT MODEL

An example demonstrating the use of document object methods is presented


below.

5/27/2022 Mrs. karthiga g 18cs63 63


THE DOCUMENT OBJECT MODEL

Element Node Object


✔The type of object returned by the method
document.getElementById() is an element node object.

✔This represents an HTML element in the hierarchy, contained


between the opening <> and closing </> tags.

✔Since IDs must be unique in an HTML document,


getElementByID() returns a single node that has the mentioned ID.

✔We have already seen some common properties of elements. Some


more properties associated with the element objects are listed next.

5/27/2022 Mrs. karthiga g 18cs63 64


THE DOCUMENT OBJECT MODEL

✔The above properties are available for all HTML elements.

✔There are some HTML elements that have additional properties that can be accessed. These
properties are listed next.
5/27/2022 Mrs. karthiga g 18cs63 65
THE DOCUMENT OBJECT MODEL

Some Specific HTML DOM Element Properties for Certain Tag Types

5/27/2022 Mrs. karthiga g 18cs63 66


THE DOCUMENT OBJECT MODEL

Modifying a DOM Element


✔In this section we see how to modify the contents of various elements in a
HTML document using JavaScript.

✔For this, we first have a look at the most popular ways of displaying a
JavaScript output.

✔A JavaScript output is displayed using one of the following two popular


approaches:
innerHTML property
alert() method

✔Using the innerHTML property, we can display the output of a JavaScript


code within a HTML element.

5/27/2022 Mrs. karthiga g 18cs63 67


THE DOCUMENT OBJECT MODEL

✔To accomplish this, we must first be able to access a specific HTML


element.

✔We know that a HTML element is uniquely identified using the id


attribute.

✔In order to access an element with a specific ID in our JavaScript


code, we use the document.getElementById(id) method.

✔Once the element has been accessed, we can then add contents into
that element using the innerHTML property.

✔innerHTML property example

5/27/2022 Mrs. karthiga g 18cs63 68


THE DOCUMENT OBJECT MODEL

✔alert() method is another popular method of displaying a JavaScript output.

✔The alert() method displays the content that we pass to it as parameter in a


pop up window.

✔alert() method demo

✔With this background let us now see how to modify the contents of an
element.

✔Consider the following HTML element,


<div id = "latestComment">
<p>By Ricardo on <time>September 15, 2012</time></p>
<p>Easy on the HDR buddy.</p>
</div>

5/27/2022 Mrs. karthiga g 18cs63 69


THE DOCUMENT OBJECT MODEL

✔We now modify the contents of this <div> element using JavaScript as
follows.
var latest = document.getElementById("latestComment");
var oldMessage = latest.innerHTML;
latest.innerHTML = oldMessage + "<p>Updated this div with
JS</p>";

✔The resulting <div> element is


<div id = "latestComment">
<p>By Ricardo on <time>September 15, 2012</time></p>
<p>Easy on the HDR buddy.</p>
<p>Updated this div with JS</p>
</div>

5/27/2022 Mrs. karthiga g 18cs63 70


THE DOCUMENT OBJECT MODEL

A More Verbose Technique


Here we see some more JavaScript methods that can modify contents of
a HTML document.

Some of the methods that we will be seeing are createTextNode(),


removeChild() and appendChild().

createTextNode()
The createTextNode() method creates a Text Node with the specified
text.
var t = document.createTextNode("Hello World");

Once a text node has been created, we create an element to hold this text
node.

5/27/2022 Mrs. karthiga g 18cs63 71


THE DOCUMENT OBJECT MODEL

✔To create an element, we use the createElement() method.


var para = document.createElement(“P");

✔Once the element is created, the text node in put into the element using the
appendChild() method.

✔The appendChild() method appends a node as the last child of a node.


var node = document.createElement("LI"); // Create a <li> node
var textnode = document.createTextNode("Water"); // Create a text node
node.appendChild(textnode); // Append the text to <li>

createTextNode demo1
createTextNode demo2
appendChild demo

5/27/2022 Mrs. karthiga g 18cs63 72


THE DOCUMENT OBJECT MODEL

removeChild()
The removeChild() method removes a specified child node of the
specified element.
var list = document.getElementById("myList");
list.removeChild(list.childNodes[0]);

removeChild demo

Changing an Element’s Style – style property


We can change the style definition of a specific element dynamically
using the style property in the JavaScript code.
element.style.property //returns a style property
element.style.property = value // sets style property

5/27/2022 Mrs. karthiga g 18cs63 73


THE DOCUMENT OBJECT MODEL

✔style property demo1


✔style property demo2

className property
✔Another way of dynamically defining the style of an element is using
the className property.

✔The className property sets or returns the class name of an element.

✔Syntax
HTMLElementObject.className //Return the className
HTMLElementObject.className = class //Set the className

5/27/2022 Mrs. karthiga g 18cs63 74


THE DOCUMENT OBJECT MODEL

className property demo1


className property demo2
className property demo3
className property demo4

Additional Properties
value property
The value property sets or returns the value of the of a text field.

Value property demo

5/27/2022 Mrs. karthiga g 18cs63 75


JAVASCRIPT EVENTS

✔A JavaScript Event is an action that can be detected by JavaScript.

✔Many of the events are initiated by user actions but some are generated by the
browser itself.

✔When an event occurs, we say that an event is triggered.

✔This triggered event is then caught by JavaScript functions, which then do


something in response.

✔There are several approaches by which JavaScript can handle events. The
popular approaches are:
✔Inline event handling
✔Listener approach

5/27/2022 Mrs. karthiga g 18cs63 76


JAVASCRIPT EVENTS

Inline Event Handler Approach


✔As the name says, in this approach the HTML markup and the
corresponding JavaScript logic are woven together.

✔This reduces the ability of designers to work separately from


programmers, and generally complicates maintenance of applications.

✔This is against the philosophy of HTML being a sematic markup.

✔Inline even handler demo

✔In the above example, the event that occurs is click and the handler to
that event is alert() method that displays a pop-up.

5/27/2022 Mrs. karthiga g 18cs63 77


JAVASCRIPT EVENTS

Listener Approach
✔The problem with the inline handler approach is that it does not make use of
layers, that is, it does not separate content from behaviour.

✔The listener approach separates all JavaScript code from the HTML
markup.

✔A basic example demonstrating the listener approach for event handling is


presented below.

var greetingBox = document.getElementById('example1');


greetingBox.onclick = alert('Good Morning');
✔The main advantage of this approach is that, this code can be written
anywhere, including an external file that helps uncouple the HTML from
the JavaScript.
5/27/2022 Mrs. karthiga g 18cs63 78
JAVASCRIPT EVENTS

✔One limitation with this approach (and the inline approach) is that only one
handler can respond to any given element event.

✔This means, once a event handler has been defined for an element, no other
handler can be defined for the same element using the approach demonstrated
now.

✔This limitation is overcome in DOM2 version.

✔DOM2 introduces the addEventListener() method using which multiple event


handlers can be added to one element.

✔The addEventListener() method attaches an event handler to an element


without overwriting existing event handlers.

5/27/2022 Mrs. karthiga g 18cs63 79


JAVASCRIPT EVENTS

Syntax
element.addEventListener(event, function);

✔The first parameter is the type of the event (like "click" or "mousedown" or
any other HTML DOM Event.)

✔The second parameter is the function we want to call when the event occurs.

Eventlistener demo1
Eventlistener demo2
Eventlistener demo3

✔Some more example of event handling using a user defined function and an
anonymous function is presented next.

5/27/2022 Mrs. karthiga g 18cs63 80


JAVASCRIPT EVENTS

Event Handling using User Defined function

Event Handling using Anonymous function


5/27/2022 Mrs. karthiga g 18cs63 81
JAVASCRIPT EVENTS

Event Object
✔All the events that we encounter are DOM event objects.

✔Typically, an event is passed to its handler as a parameter named e,


where e is the event object.
function someHandler(e) {
// e is the event that triggered this handler.
}

✔An event object has several key properties. Some of them are:
✔Bubbles
✔Cancelable
✔preventDefault

5/27/2022 Mrs. karthiga g 18cs63 82


JAVASCRIPT EVENTS

Bubbles
✔The Bubbles property is a Boolean value.

✔If an event’s bubbles property is set to true then there must be an event handler
in place to handle the event.

✔If not, the event will bubble up to its parent and trigger an event handler there.

✔If the parent has no handler it continues to bubble up until it hits the document
root, and then it goes away, unhandled.

✔Syntax
event.bubbles // returns TRUE or FALSE

5/27/2022 Mrs. karthiga g 18cs63 83


JAVASCRIPT EVENTS

Cancelable
✔The Cancelable property is also a Boolean value that indicates whether
or not the event can be cancelled.

✔An event is cancelable if it is possible to prevent the events default


action.

✔A common example is a user clicking on a link. The default action is


to follow the link and load the new page.

✔If this default action can be cancelled, an event is said to be cancelable.


event.cancelable //returns TRUE or FALSE

5/27/2022 Mrs. karthiga g 18cs63 84


JAVASCRIPT EVENTS

preventDefault
The default action of an event is canceled using the preventDefault()
method.

preventDefault() method demo

5/27/2022 Mrs. karthiga g 18cs63 85


JAVASCRIPT EVENTS

Event types
✔There are several classes of events, with several types of event within each
class specified by the W3C.

✔The classes are:


▪Mouse events
▪Keyboard events
▪Form events
▪Frame events.

✔Mouse Events
✔Mouse events are defined to capture a range of interactions driven by the
mouse.

5/27/2022 Mrs. karthiga g 18cs63 86


JAVASCRIPT EVENTS

✔The mouse events can be further categorized as mouse click and mouse move
events.

✔Some of the mouse events are tabulated below.

5/27/2022 Mrs. karthiga g 18cs63 87


JAVASCRIPT EVENTS

✔Many mouse events can happen at a time.

✔The user could be moving the mouse off one <div> and onto another in the
same moment, triggering onmouseon and onmouseout events as well as the
onmousemove event.

✔Mouse event sdemo

✔Keyboard Events
Events that occur when user presses a key on the keyboard, belongs to the
KeyboardEvent Object.

✔The various types of keyboard events are discussed next.

5/27/2022 Mrs. karthiga g 18cs63 88


JAVASCRIPT EVENTS

✔The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC)
in all browsers.

✔Hence it is better to use the onkeydown event instead, because it works for all
keys.

✔Keyboard events demo

5/27/2022 Mrs. karthiga g 18cs63 89


JAVASCRIPT EVENTS

Form Events
Forms are the main means by which user input is collected and transmitted
to the server.

5/27/2022 Mrs. karthiga g 18cs63 90


JAVASCRIPT EVENTS

✔The events triggered by forms allow us to do some timely processing in


response to user input.

✔The most common JavaScript listener for forms is the onsubmit event.

✔Form events demo

5/27/2022 Mrs. karthiga g 18cs63 91


FORMS

In this section we will be seeing how to validate certain aspects of a form and how a
form is submitted.

Consider the following form,

<form action='login.php' method='post' id='loginForm'>


<input type='text' name='username' id='username'/>
<input type='password' name='password' id='password'/>
<input type='submit'></input>
</form>
Validating Forms

Form validation is one of the most common applications of JavaScript.

Writing code to prevalidate forms on the client side will reduce the number of
incorrect submissions, thereby reducing server load.

5/27/2022 Mrs. karthiga g 18cs63 92


FORMS

✔There are a number of common validation activities including email


validation, number validation, and data validation. We will discuss
some of them.

Empty Field Validation


✔A common application of a client-side validation is to make sure the
user entered something into a field.

✔There’s certainly no point sending a request to log in if the username


was left blank, so why not prevent the request from working?

✔The way to check for an empty field in JavaScript is to compare a


value to both null and the empty string ("") to ensure it is not empty

5/27/2022 Mrs. karthiga g 18cs63 93


FORMS

A simple validation script to check for empty fields is presented below,


document.getElementById("loginForm").onsubmit = function(e){
var fieldValue=document.getElementByID("username").value;
if(fieldValue==null || fieldValue== ""){
// the field was empty. Stop form submission
e.preventDefault();
// Now tell the user something went wrong
alert("you must enter a username");
}
}
Number Validation
One of the popular functions used to test for numeric values is the isNumeric()
function.

This method checks whether its argument represents a numeric value. If so, it
returns true. Otherwise it returns false. The argument can be of any type.
5/27/2022 Mrs. karthiga g 18cs63 94
FORMS

Submitting Forms
Submitting a form using JavaScript requires having a node variable for the
form element.

Once the variable, say, formExample is acquired, one can simply call the
submit() method:

var formExample = document.getElementById("loginForm");


formExample.submit();

5/27/2022 Mrs. karthiga g 18cs63 95


INTRODUCTION TO SERVER – SIDE DEVELOPMENT WITH PHP

What Is Server-Side Development?


✔Website content such as HTML, CSS and images has to be housed on a
server to be viewable online.

✔For this, Web Hosting is needed. Web Hosting is the process of renting or
buying space to house a website on the World Wide Web.

✔Web hosting is not the only responsibility of a web server.

✔Server-side development is much more than web hosting.

✔It involves the use of a programming technology like PHP or ASP.NET to


create scripts that dynamically generate content.

5/27/2022 Mrs. karthiga g 18cs63 96


WHAT IS SERVER – SIDE DEVELOPMENT

✔It is important to remember that when developing server-side scripts, we are


writing software, just like a C or Java programmer would do.

✔However, the major distinction is that our software runs on a web server
and uses the HTTP request-response loop for most interactions with the
clients.

Comparing Client and Server Scripts


JavaScript is a client side programming language(script) that we are
familiar with.

In a client-side script the code is executed on the client browser, whereas in


a server-side script, it is executed on the web server.

5/27/2022 Mrs. karthiga g 18cs63 97


WHAT IS SERVER – SIDE DEVELOPMENT

✔Client side JavaScript code is downloaded at the client and is executed there.

✔In contrast, server-side source code remains hidden from the client as it is
processed on the server.

✔The clients never get to see the code. Only the HTML output from the script
is seen.

✔A server script can access resources on the web server whereas the client
cannot.

✔The following figure illustrates how client and server scripts differ.

5/27/2022 Mrs. karthiga g 18cs63 98


WHAT IS SERVER – SIDE DEVELOPMENT

5/27/2022 Mrs. karthiga g 18cs63 99


WHAT IS SERVER – SIDE DEVELOPMENT

Server-Side Script Resources


✔A server-side script can access any resources made available to it by the
server.

✔These resources can be categorized as data storage resources, web services


and software applications.

Server scripts have access


to many resources

5/27/2022 Mrs. karthiga g 18cs63 100


WHAT IS SERVER – SIDE DEVELOPMENT

✔The most commonly used resource is Data Storage, often in the form of a
connection to a Database Management System.

✔A Database Management System (DBMS) is a software system for storing,


retrieving, and organizing large amounts of data.

✔The server’s File System is used by websites as a place to store user


uploads.

✔The next suites of resources are Web Services, often offered by third-party
providers.

✔Web services use the HTTP protocol to return XML or other data formats.

5/27/2022 Mrs. karthiga g 18cs63 101


WHAT IS SERVER – SIDE DEVELOPMENT

A Web Service is can be defined by following ways:


✔It is a client-server application or application component for
communication.
✔The method of communication between two devices over the network.
✔It is a software system for the interoperable machine to machine
communication.
✔It is a collection of standards or protocols for exchanging information
between two devices or application.

5/27/2022 Mrs. karthiga g 18cs63 102


WHAT IS SERVER – SIDE DEVELOPMENT

Using other software means, server applications can also send and receive
email, access user authentication services etc.

Comparing Server-Side Technologies

Here, we discuss the most common server-side technologies used for


creating web applications.

ASP(Active Server Pages)


✔Microsoft’s first server-side technology (also called ASP Classic).
✔Like PHP, ASP code can be embedded within the HTML.
✔ASP programming code is interpreted at run time.
✔ASP supports classes and some object-oriented features, but this facility
was not utilized by most developers.

5/27/2022 Mrs. karthiga g 18cs63 103


WHAT IS SERVER – SIDE DEVELOPMENT

ASP.NET
✔ASP.NET is part of Microsoft’s .NET Framework and can use any .NET
programming language like C#.

✔ASP.NET uses an explicitly object-oriented approach and that is why it takes longer
to learn ASP.NET than ASP or PHP.

✔ASP.NET uses special markup called web server controls that encapsulate common
web functionality such as database-driven lists, form validation, and user registration
wizards.

✔ASP.NET pages are compiled into an intermediary file format called MSIL that is
analogous to Java’s byte-code.

✔ASP.NET then uses a JIT (Just-In-Time) compiler to compile the MSIL into machine
executable code.

✔ASP.NET is essentially limited to Windows servers.


5/27/2022 Mrs. karthiga g 18cs63 104
WHAT IS SERVER – SIDE DEVELOPMENT

JSP (Java Server Pages)


✔JSP uses Java as its programming language and like ASP.NET it uses an
explicit object-oriented approach.
✔It is integrated into the J2EE environment.
✔Since JSP uses the Java Runtime Engine, it also uses a JIT compiler for
fast execution time and is cross-platform.

Node.js
✔This is a more recent server environment that uses JavaScript on the server
side.
✔Unlike the other development technologies listed here, node.js is also its
own web server software, thus eliminating the need for Apache, IIS, or
some other web server software.

5/27/2022 Mrs. karthiga g 18cs63 105


WHAT IS SERVER – SIDE DEVELOPMENT

Perl
✔Perl was the language typically used for early server-side web development.
✔It was commonly used in conjunction with the Common Gateway Interface
(CGI), an early standard API for communication between applications and
web server software.

PHP(Hypertext Processor)
✔PHP is a dynamically typed language that can be embedded directly within
the HTML.
✔By default, PHP pages are compiled into an intermediary representation
called opcodes that are analogous to Java’s byte-code or the .NET
Framework’s MSIL.

5/27/2022 Mrs. karthiga g 18cs63 106


WHAT IS SERVER – SIDE DEVELOPMENT

Python
✔Python is an object-oriented programming language has many uses,
including being used to create web applications.
✔It is also used in a variety of web development frameworks.

Ruby on Rails
✔This is a web development framework that uses the Ruby programming
language.
✔Like ASP.NET and JSP, Ruby on Rails also emphasizes the use of MVC
design pattern.
✔It integrates features such as templates and engines that aim to reduce the
amount of development work required in the creation of a new site.

5/27/2022 Mrs. karthiga g 18cs63 107


A WEB SERVER RESPONSIBILITY

A web server has many responsibilities:

• Handling HTTP connections


• Responding to requests for static and dynamic resources
• Managing permissions and access for certain resources
• Encrypting and compressing data
• Managing multiple domains and URLs
• Managing database connections
• Managing cookies and state
• Uploading and managing files

5/27/2022 Mrs. karthiga g 18cs63 108


LAMP STACK

You will be using the LAMP software stack

• Linux operating system


• Apache web server
• MySQL DBMS
• PHP scripting language

5/27/2022 Mrs. karthiga g 18cs63 109


APACHE AND LINUX

• Consider the Apache web server as the intermediary that


interprets HTTP requests that arrive through a network port
and decides how to handle the request, which often requires
working in conjunction with PHP.

5/27/2022 Mrs. karthiga g 18cs63 110


APACHE

✔Apache runs as a daemon on the server. A daemon is an


executing instance of a program (also called a process) that
runs in the background, waiting for a specific event that will
activate it.

✔When a request arrives, Apache then uses modules to


determine how to respond to the request.

✔In Apache, a module is a compiled extension (usually written


in the C programming language) to Apache that helps it
handle requests. For this reason, these modules are also
sometimes referred to as handlers.

5/27/2022 Mrs. karthiga g 18cs63 111


APACHE AND PHP

5/27/2022 Mrs. karthiga g 18cs63 112


APACHE THREADS

Apache runs in two possible modes:


• multi-process (also called preforked)
• multi-threaded (also called worker)

The default installation of Apache runs using the


multi-process mode.

5/27/2022 Mrs. karthiga g 18cs63 113


APACHE THREADS

5/27/2022 Mrs. karthiga g 18cs63 114


PHP INTERNALS

There are 3 main modules


1. PHP core. The Core module defines the main features of
the PHP environment, including essential functions for
variable handling, arrays, strings, classes, math, and other
core features.
2. Extension layer. This module defines functions for
interacting with services outside of PHP. This includes
libraries for MySQL, FTP, SOAP web services, and XML
processing, among others.
3. Zend Engine. This module handles the reading in of a
requested PHP file, compiling it, and executing it.

5/27/2022 Mrs. karthiga g 18cs63 115


ZEND ENGINE

5/27/2022 Mrs. karthiga g 18cs63 116


INSTALLING LAMP LOCALLY

The easiest and quickest way to do so is to use the


• XAMPP For Windows installation package
• MAMP for Mac installation package
Both of these installation packages install and configure
Apache, PHP, and MySQL.
Later we can come back and configure these systems in more
detail.

5/27/2022 Mrs. karthiga g 18cs63 117


XAMPP Control Panel

5/27/2022 Mrs. karthiga g 18cs63 118


XAMPP Settings

• PHP requests in your browser will need to use the localhost


domain (127.0.0.1)
• PHP files will have to be saved somewhere within the
C:\xampp\htdocs folder

5/27/2022 Mrs. karthiga g 18cs63 119


QUICK TOUR

• PHP, like JavaScript, is a dynamically typed


language.
• It uses classes and functions in a way consistent
with other object-oriented languages such as C++,
C#, and Java
• The syntax for loops, conditionals, and assignment
is identical to JavaScript
• Differs when you get to functions, classes, and in
how you define variables

5/27/2022 Mrs. karthiga g 18cs63 120


PHP TAG

• The most important fact about PHP is that the


programming code can be embedded directly
within an HTML file.
• A PHP file will usually have the extension .php
• programming code must be contained within an
opening <?php tag and a matching closing ?>
tag
• any code outside the tags is echoed directly out
to the client

5/27/2022 Mrs. karthiga g 18cs63 121


PHP TAG

5/27/2022 Mrs. karthiga g 18cs63 122


HTML AND PHP

5/27/2022 Mrs. karthiga g 18cs63 123


HTML AND PHP

5/27/2022 Mrs. karthiga g 18cs63 124


PHP COMMENTS

The types of comment styles in PHP are:

• Single-line comments. Lines that begin with a # are comment


lines and will not be executed.
• Multiline (block) comments. These comments begin with a /*
and encompass everything that is encountered until a closing
*/ tag is found.
• End-of-line comments. Whenever // is encountered in code,
everything up to the end of the line is considered a comment.

5/27/2022 Mrs. karthiga g 18cs63 125


PHP COMMENTS

<?php
# single-line comment
/*
This is a multiline comment.
They are a good way to document
functions or complicated blocks of
code
*/
$artist = readDatabase(); //
end-of-line comment
?>

5/27/2022 Mrs. karthiga g 18cs63 126


VARIABLES

✔Variables in PHP are dynamically typed.


✔Variables are also loosely typed in that a variable can be
assigned different data types over time
✔To declare a variable you must preface the variable name
with the dollar ($) symbol.

$count = 42;

5/27/2022 Mrs. karthiga g 18cs63 127


DATA TYPES

Data Type Description

Boolean A logical true or false value

Integer Whole numbers

Float Decimal numbers

String Letters

Array A collection of data of any type (covered in the next chapter)

Object Instances of classes

5/27/2022 Mrs. karthiga g 18cs63 128


CONSTANTS

A constant is somewhat similar to a variable, except a


constant’s value never changes . . . in other words it stays
constant.
• Typically defined near the top of a PHP file via the define()
function
• once it is defined, it can be referenced without using the $
symbol

5/27/2022 Mrs. karthiga g 18cs63 129


FUNCTIONS

Just as with any language, writing code in the main function (which in
PHP is equivalent to coding in the markup between <?php and ?>
tags) is not a good habit to get into.
A function in PHP contains a small bit of code that accomplishes one
thing. In PHP there are two types of function: user-defined functions
and built-in functions.
1. A user-defined function is one that you the programmer define.
2. A built-in function is one of the functions that come with the
PHP environment

5/27/2022 Mrs. karthiga g 18cs63 130


FUNCTIONS

While the example function in Listing 8.13 returns a value, there is no


requirement for this to be the case.

5/27/2022 Mrs. karthiga g 18cs63 131


FUNCTIONS

5/27/2022 Mrs. karthiga g 18cs63 132


CALL A FUNCTION

Now that you have defined a function, you are able to use it
whenever you want to. To call a function you must use its name
with the () brackets.

Since getNiceTime() returns a string, you can assign that return


value to a variable, or echo that return value directly, as shown
below.

$output = getNiceTime();
echo getNiceTime();
If the function doesn’t return a value, you can just call the
function:
outputFooterMenu();

5/27/2022 Mrs. karthiga g 18cs63 133


PARAMETERS

Parameters are the mechanism by which values are passed into


functions.

To define a function with parameters, you must decide


• how many parameters you want to pass in,
• and in what order they will be passed
• Each parameter must be named

5/27/2022 Mrs. karthiga g 18cs63 134


PARAMETERS

Parameters are the mechanism by which values are passed into


functions.

To define a function with parameters, you must decide


• how many parameters you want to pass in,
• and in what order they will be passed
• Each parameter must be named

5/27/2022 Mrs. karthiga g 18cs63 135


PARAMETERS

Thus to call our function, you can now do it in two ways:

echo getNiceTime(1); // this will print seconds


echo getNiceTime(0); // will not print seconds

5/27/2022 Mrs. karthiga g 18cs63 136


PARAMETER DEFAULT VALUES

Now if you were to call the function with no values, the


$showSeconds parameter would take on the default value, which we
have set to 1, and return the string with seconds.

5/27/2022 Mrs. karthiga g 18cs63 137


PASS PARAMETER DEFAULT VALUES

By default, arguments passed to functions are passed by value


in PHP. This means that PHP passes a copy of the variable so if
the parameter is modified within the function, it does not
change the original.

5/27/2022 Mrs. karthiga g 18cs63 138


PASS PARAMETER BY REFERENCES

PHP also allows arguments to functions to be passed by reference, which will


allow a function to change the contents of a passed variable.
The mechanism in PHP to specify that a parameter is passed by reference is to add
an ampersand (&) symbol next to the parameter name in the function declaration

5/27/2022 Mrs. karthiga g 18cs63 139


VALUE vs REFERENCES

5/27/2022 Mrs. karthiga g 18cs63 140


PARAMETERS
All variables defined within a function (such as parameter variables) have
function scope, meaning that they are only accessible within the function.
Any variables created outside of the function in the main script are
unavailable within a function.
$count= 56;
function testScope() {
echo $count; // outputs 0 or generates run-time
//warning/error
}
testScope();
echo $count; // outputs 56
5/27/2022 Mrs. karthiga g 18cs63 141
PARAMETERS

✔Variables defined in the main script are said to have global scope.

✔Unlike in other programming languages, a global variable is not, by default,


available within functions.

✔PHP does allow variables with global scope to be accessed within a function
using the global keyword

5/27/2022 Mrs. karthiga g 18cs63 142

You might also like