Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views61 pages

CSC506 Web

Web

Uploaded by

estherelisha022
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)
9 views61 pages

CSC506 Web

Web

Uploaded by

estherelisha022
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/ 61

MODIBBO ADAMA UNIVERSITY, YOLA

DEPARTMENT OF COMPUTER SCIENCE

CSC506: WEB AND INTERNET


PROGRAMMING
(3 Units)

Textbooks:
• Web programming with HTML5, CSS, and JavaScript by John Dean
• Learning PHP, MySQL & JavaScript by Robin Nixon
• Web programming and Internet technologies, an E-commerce approach
by MaPawan Lingras Porter Scobey.
• Web Programming_ Building Internet Applications-Wiley by Chris Bates.
• JavaScript – JavaScript language: tutorials-point Simply Easy Learning.
.

Course Lecturer: Mr. A. A. Kadams 1|


Page
UNDERSTANDING THE WWW AND THE INTERNET
Internet: The Internet is a global system of interconnected computer networks that
use the standard Internet Protocol Suite (TCP/IP) to serve billions of users
worldwide. It is a network of networks that consists of millions of private, public,
academic, business, and government networks.

WWW: The World Wide Web, abbreviated as WWW and commonly known as the
Web, is a system of interlinked hypertext documents accessed via the Internet.
With a web browser, one can view web pages that may contain text, images,
videos, and other multimedia and navigate between them via hyperlinks.

Emergence of Web: Between the summers of 1991 and 1994, the load on the first
Web server ("info.cern.ch") rose steadily by a factor of 10 every year.
In 1992, academia and in 1993 industry were taking notice. The World Wide Web
Consortium was formed in September 1994, with a base at MIT in the USA, INRIA
in France, and now also at Keio University in Japan. With the dramatic flood of rich
material of all kinds onto the Web in the 1990s, the first part of the dream is largely
realized, although still very few people in practice have access to intuitive hypertext
creation tools.
The second part has yet to happen, but there are signs and plans that make us
confident. The great need for information about information, to help us categorize,
sort, and pay for our own information, is driving the design of languages for the
web, designed for processing by machines, rather than people. The web of human-
readable documents is being merged with a web of machine-understandable data.
The potential of the mixture of humans and machines working together and
communicating through the web could be immense.

WEB Servers: To view and browse pages on the Web, all you need is a web
browser. To publish pages on the Web, you need a web server. A web server is
the program that runs on a computer and is responsible for replying to web browser
requests for files. You need a web server to publish documents on the Web. When
you use a browser to request a page on a website, that browser makes a web
connection to a server using the HTTP protocol. The browser then formats the
information it got from the server. The server accepts the connection, sends the
contents of the requested files, and then closes.

WEB Browsers:
A web browser is the program you use to view pages and navigate the World Wide
Web. A wide array of web browsers is available for just about every platform you
can imagine. Microsoft Internet Explorer, for example, is included with Windows,
and Safari is included with Mac OS X. Mozilla Firefox, Netscape Navigator, and
Opera are all available for free. What the Browser Does The core purpose of a web
browser is to connect to web servers, request documents, and then properly format
and display those documents. Web browsers can also display files on your local
Course Lecturer: Mr. A. A. Kadams 2|
Page
computer and download files that are not meant to be displayed. Each web page
is a file written in a language called the Hypertext Markup Language (HTML) that
includes the text of the page, a description of its structure, and links to other
documents, images, or other media.

Protocols: In computing, a protocol is a set of rules which is used by computers


to communicate with each other across a network. A protocol is a convention or
standard that controls or enables the connection, communication, and data transfer
between computing endpoints.

Internet Protocol Suite: The Internet Protocol Suite is the set of communications
protocols used for the Internet and other similar networks. It is commonly also
known as TCP/IP, named from two of the most important protocols in it: The
Transmission Control Protocol (TCP) and the Internet Protocol (IP), which were
the first two networking protocols defined in this standard.

Building websites: It's a good idea to first think about and design your site. That
way, you'll give yourself directions, and you'll need to reorganize less later.
To design your site:
1. Figure out why you're creating this site. What do you want to convey?
2. Think about your audience. How can you tailor your content to appeal to this
audience? For example, should you add lots of graphics, or is it more
important that your page downloads quickly?
3. How many pages will you need? What sort of structure would you like it to
have? Do you want visitors to go through your site in a particular direction, or
do you want to make it easy for them to explore in any direction?
4. Sketch out your site on paper. Devise a simple, consistent naming system for
your pages, images, and other external files.

HOW DO WEB BROWSERS AND WEB SERVERS


COMMUNICATE?

WEB PROTOCOL:
A web protocol is, similarly, an agreed-upon set of rules and data formats to be
used when two or more computers or other devices, or application programs
running on those machines, wish to communicate across the Internet, usually but
not always on behalf of human users. In any given communication, it is likely that
there will be several different protocols involved.
Common web protocols
There are many protocols in use on the web. Here is a very short list of some of
the more common ones:
• TCP/IP (Transmission Control Protocol/Internet Protocol), a two-part
protocol that underlies pretty much everything that travels over the web. This
Course Lecturer: Mr. A. A. Kadams 3|
Page
is the low-level “lingua franca” of the World Wide Web. If TCP/IP went away
tomorrow, the web would cease to exist. One of the reasons it is so widely
used is that it guarantees delivery of the information that was sent.
• UDP (User Datagram Protocol), another protocol that can also be used as
the underlying transport protocol for information, and though it may be faster
to use if you are moving large multimedia files (for example), it does not
guarantee that all of the information will arrive safely. This may not be an
important consideration if you do not care that your final photograph is
missing a pixel or two.
• HTTP (Hypertext Transfer Protocol), the protocol that browsers use to
send requests for information to servers and that a server uses to send
requested information back to a browser.
• FTP (File Transfer Protocol), the protocol used to transfer files from one
computer to another across the Internet.
• TELNET (TELephone NETwork) and SSH (Secure SHell) are both
protocols that can provide “terminal emulation” when used to connect, over
the Internet, to a remote computer and log in to an account on that computer.
TELNET has been around for many years, but its use is discouraged these
days because of security concerns, in favor of SSH, which is a more secure
protocol for the transfer of information.
STUDY WORK: What do you understand by the following terms?
▪ IP addresses
▪ Host machines and domains
▪ The domain name system and domain name servers
▪ URLs, URNs, and URIs

HTML FOR CONTENT STRUCTURE


The first documents on the World Wide Web were created using the original, and
very primitive, version of the Hypertext Markup Language (HTML). The history of
HTML goes back to 1980, when Tim Berners-Lee, a physicist, began to create a
system for sharing documents among fellow physicists. The first specification for
HTML was eventually published in 1991 by Berners-Lee, and HTML subsequently
evolved through several standards, until its development was essentially “frozen”
at version 4.01. Then along came XHTML, which was essentially HTML rewritten
to comply with the much stricter standards of XML, and for a while, this became a
commonly accepted standard for use by all web browsers and developers. XHTML
is very similar to HTML, and many people regard it as an improvement over HTML
because it requires developers to be more careful and consistent when writing
markup code. Unfortunately, as time went on, the web community decided it
wanted less strict standards, rather than more, so further development of the
XHTML standard stalled, and work on XHTML 2 was eventually halted altogether,
in late 2009. See TABLE 3.1 for a brief summary of HTML and XHTML history.
Course Lecturer: Mr. A. A. Kadams 4|
Page
Although XHTML is no longer the standard that you should follow, it had many
“rules” that you can still use as “guidelines” when you write your HTML markup,
and doing so will result in much “better” web pages. We will provide more details
on this approach later, and we recommend that all new web page markup code
(including yours) be written using the guidelines we will present. And if, by chance,
you have already written some XHTML markup using its much stricter rules, there
is virtually nothing you will have to “unlearn”.
Table 3.2: Comparison of HTML and XHTML
Criteria HTML XHTML
Syntax Tolerates errors Strict syntax rules
Case Sensitivity Not case-sensitive Tags must be lowercase
Tag Closure Optional for some tags All tags must be closed
Parsing Browser-based XML parser
MIME Type text/html application/xhtml+xml

Table 3.3: Key Differences Between HTML and HTML5


Feature HTML HTML5
Doctype <!DOCTYPE HTML PUBLIC ...> <!DOCTYPE html>
Audio/Video Tags Not supported <audio>, <video> supported
Graphics Only via external plugins (e.g., Flash) <canvas>, <svg> supported
Error Handling Less forgiving More flexible and forgiving

Course Lecturer: Mr. A. A. Kadams 5|


Page
PLANNING FOR DESIGNING WEB PAGES:
Breaking Up Your Content into Main Topics
With your goals in mind, try to organize your content into main topics or sections,
chunking related information together under a single topic. Ideas for Organization
and Navigation. At this point, you should have a good idea of what you want to talk
about as well as a list of topics. The next step is to actually start structuring the
information you have into a set of web pages. Before you do that, however,
consider some standard structures that have been used in other help systems and
online tools. This section describes some of these structures, their various
features, and some important considerations, including the following
Model and Structure of a Website:
You need to know what the following terms mean and how they apply to the body
of work you're developing for the Web:
Website: A collection of one or more web pages linked together in a meaningful
way that, as a whole, describes a body of information or creates an overall effect.
Web server: A computer on the Internet or an intranet that delivers Web pages and
other files in response to browser requests.
Web page: A single document on a website, usually consisting of an HTML
document and any items that are displayed within that document such as inline
images.
Home page: The entry page for a website, which can link to additional pages on
the same website or pages on other sites.
Developing websites: Designing a website, like designing a book outline, a
building plan, or a painting, can sometimes be a complex and involved process.
Having a plan before you begin can help you keep the details straight and help you
develop the finished product with fewer false starts. Today, you learned how to put
together a simple plan and structure for creating a set of web pages, including the
following:
• Deciding what sort of content to present
• Coming up with a set of goals for that content
• Deciding on a set of topics
• Organizing and storyboarding the website
Basic HTML: HTML stands for Hypertext Markup Language. The idea here is that
most documents have common elements for example, titles, paragraphs, and lists.
Before you start writing, therefore, you can identify and define the set of elements
in that document and give them appropriate names.

How Markup Works


HTML is a markup language. Writing in a markup language means that you start
with the text of your page and add special tags around words and paragraphs. The
tags indicate the different parts of the page and produce different effects in the
browser. HTML has a defined set of tags you can use. You can't make up your
own tags to create new styles or features.
What HTML Files Look Like

Course Lecturer: Mr. A. A. Kadams 6|


Page
Pages written in HTML are plain text files (ASCII), which means that they contain
no platform- or program-specific information. Any editor that supports text can read
them. HTML files contain the following:
• The text of the page itself
• HTML tags that indicate page elements, structure, formatting, and hypertext
links to other pages or to included media. Most HTML tags look something
like the following: <the-tag-name>affected text</the-tag-name>
The tag name itself (here, the-tag-name) is enclosed in brackets (< >). HTML tags
generally have a beginning and an ending tag surrounding the text they affect. The
beginning tag "turns on" a feature (such as headings, bold, and so on), and the
ending tag turns it off. Closing tags have the tag name preceded by a slash (/). The
opening tag (for example, <p> for paragraphs) and closing tag (for example, </p>
for paragraphs) compose what is officially called an HTML element.
TEXT FORMATTING AND HTML
When an HTML page is parsed by a browser, any formatting you might have done
by hand that is, any extra spaces, tabs, returns, and so on is ignored. The only
thing that specifies formatting in an HTML page is an HTML tag. If you spend hours
carefully editing a plain text file to have nicely formatted paragraphs and columns
of numbers but don't include any tags, when a web browser loads the page, all the
text will flow into one paragraph. All your work will have been in vain.
The advantage of having all white space (spaces, tabs, returns) ignored is that you
can put your tags wherever you want.
Let look at some examples:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>This Is Your Title</title>
</head>
<body>
<h1>This is Your Header</h1>
<p>This is your paragraph</p>
<img src="images/firefox-icon.png" alt="My test image">
</body>
</html>

Course Lecturer: Mr. A. A. Kadams 7|


Page
• <!DOCTYPE html> — doctype. It is a required preamble. In the mists of time,
when HTML was young (around 1991/92), doctypes were meant to act as
links to a set of rules that the HTML page had to follow to be considered
good HTML, which could mean automatic error checking and other useful
things. However, these days, they don't do much and are basically just
needed to make sure your document behaves correctly. That's all you need
to know for now.
• <html></html> — the <html> element. This element wraps all the content on
the entire page and is sometimes known as the root element.
• <head></head> — the <head> element. This element acts as a container
for all the stuff you want to include on the HTML page that isn't the content
you are showing to your page's viewers. This includes things
like keywords and a page description that you want to appear in search
results, CSS to style our content, character set declarations, and more.
• <meta charset="utf-8"> — This element sets the character set your
document should use to UTF-8 which includes most characters from the
vast majority of written languages. Essentially, it can now handle any textual
content you might put on it. There is no reason not to set this and it can help
avoid some problems later on.
• <title></title> — the <title> element. This sets the title of your page, which is
the title that appears in the browser tab the page is loaded in. It is also used
to describe the page when you bookmark/favorite it.
• <body></body> — the <body> element. This contains all the content that
you want to show to web users when they visit your page, whether that's
text, images, videos, games, playable audio tracks, or whatever else.
Headings

Course Lecturer: Mr. A. A. Kadams 8|


Page
Heading elements allow you to specify that certain parts of your content are
headings — or subheadings. In the same way that a book has the main
title, chapter titles, and subtitles, an HTML document can too. HTML contains 6
heading levels, <h1>–<h6>, although you'll commonly only use 3 to 4 at most:
<!-- 4 heading levels: -->
<h1>My main title</h1>
<h2>My top level heading</h2>
<h3>My subheading</h3>
<h4>My sub-subheading</h4>

Lists
A lot of the web's content is lists and HTML has special elements for these.
Marking up lists always consists of at least 2 elements. The most common list types
are ordered and unordered lists:
1. Unordered lists are for lists where the order of the items doesn't matter,
such as a shopping list. These are wrapped in a <ul> element.
2. Ordered lists are for lists where the order of the items does matter, such
as a recipe. These are wrapped in an <ol> element.

<p>At Mozilla, we’re a global community of</p>

<ul>
<li>technologists</li>
<li>thinkers</li>
<li>builders</li>
</ul>

<p>working together ... </p>

Let's explore a paragraph element a bit further to understand.

The main parts of our element are as follows:


• The opening tag: This consists of the name of the element (in this case, p),
wrapped in opening and closing angle brackets. This states where the

Course Lecturer: Mr. A. A. Kadams 9|


Page
element begins or starts to take effect — in this case where the paragraph
begins.
• The closing tag: This is the same as the opening tag, except that it includes
a forward slash before the element name. This states where the element ends
— in this case where the paragraph ends. Failing to add a closing tag is one
of the standard beginner errors and can lead to strange results.
• The content: This is the content of the element, which in this case, is just text.
• The element: The opening tag, the closing tag, and the content together
comprise the element.
Elements can also have attributes that look like the following:

Attributes contain extra information about the element that you don't want to appear
in the actual content. Here, class is the attribute name and editor-note is the
attribute value. The class attribute allows you to give the element a non-unique
identifier that can be used to target it (and any other elements with the
same class value) with style information and other things.
An attribute should always have the following:
• A space between it and the element name (or the previous attribute, if the
element already has one or more attributes).
• The attribute name followed by an equal sign.
• The attribute value wrapped by opening and closing quotation marks.
Links
Links are very important — they are what makes the web a web! To add a link, we
need to use a simple element — <a> — "a" being the short form for "anchor". To
make text within your paragraph into a link, follow these steps:
1. Choose some text. We chose the text "Mozilla Manifesto".
2. Wrap the text in an <a> element, as shown below:

<a>Mozilla Manifesto</a>

3. Give the <a> element an href attribute, as shown below:

<a href="">Mozilla Manifesto</a>

Fill in the value of this attribute with the web address that you want the link to
link to:
<a href="https://www.mozilla.org/en-US/about/manifesto/">Mozilla Manifesto</a>

Course Lecturer: Mr. A. A. Kadams 10 |


Page
You might get unexpected results if you omit the https:// or http:// part,
called the protocol, at the beginning of the web address. After making a link, click
it to make sure it is sending you where you wanted it to.

HTML Table
A table in HTML consists of table cells inside rows and columns
Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico

The HTML table:

<tr>
<table> <td>Centro comercial Moctezuma</td>
<tr> <td>Francisco Chang</td>
<th><b>Company</b></th> <td>Mexico</td>
<th><b>Contact</b></th> </tr>
<th><b>Country</b></th> </table>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>

HTML Forms

A HTML form is used to collect user input. The user input is most often sent to a
server for processing.

Form Attributes: Apart from common attributes, following is a list of the most
frequently used form attributes −
Sr.No Attribute & Description
1
action
Backend script ready to process your passed data.
2
method
Method to be used to upload data. The most frequently used are GET and
POST methods.
3
target
Specify the target window or frame where the result of the script will be
displayed. It takes values like _blank, _self, _parent etc.
4
enctype
You can use the enctype attribute to specify how the browser encodes the data
before it sends it to the server. Possible values are −
application/x-www-form-urlencoded − This is the standard method most
forms use in simple scenarios.

Course Lecturer: Mr. A. A. Kadams 11 |


Page
mutlipart/form-data − This is used when you want to upload binary data in
the form of files like image, word file etc.

HTML Form Controls

There are different types of form controls that you can use to collect data using
HTML form:-

• Text Input Controls


• Checkboxes Controls
• Radio Box Controls
• Select Box Controls
• File Select boxes
• Hidden Controls
• Clickable Buttons
• Submit and Reset Button

Text Input Controls

There are three types of text input used on forms −

• Single-line text input controls − This control is used for items


that require only one line of user input, such as search boxes or
names. They are created using HTML <input> tag.
• Password input controls − This is also a single-line text input but
it masks the character as soon as a user enters it. They are also
created using HTMl <input> tag.
• Multi-line text input controls − This is used when the user is
required to give details that may be longer than a single sentence.
Multi-line input controls are created using HTML <textarea> tag.
Example:

Here is a basic example of a single-line text input used to take Username and
Password;
<!DOCTYPE html>
<html>

<head>
<title>Text Input Control</title>
</head>

<body>
<form >
User ID: <input type = "text" name = "user_ID" />
<br>

Course Lecturer: Mr. A. A. Kadams 12 |


Page
Password: <input type = "text" name = "password" />

<input type = "radio" name = "subject" value = "maths"> Maths


<input type = "radio" name = "subject" value = "physics"> Physics

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


<input type = "reset" name = "reset" value = "Reset" />
</form>
</body>

</html>

This will produce the following result;

STUDY WORK:
▪ Differentiate between HTML and HTML5 with three (3) tag examples.
▪ Explain the differences between HTML and XHTML.
▪ Explain 3 tags each in the following; HTML Graphics, Media, APIs and
Favicon.

CASCADING STYLE SHEETS (CSS)


FOR CONTENT PRESENTATION

Previously, we introduced HTML as the markup language for describing the


structure of a web page. Thus we use HTML tags to mark the parts of our pages
that are headings, paragraphs, list items, and so on.
Every browser will have its own default way of displaying each of these structures,
and often these defaults are perfectly adequate for our purposes. On the other
hand,
there are also many times when we wish to take control of how our pages look,
and
where on those pages our information is to be displayed. For example, we may
want a different font size or text color, or we may want two columns of text rather
than one, and that is where Cascading Style Sheets (CSS) come into play.

A CSS style rule is a rule that tells a browser how some part of a web page is to
be displayed. For example, here are two simple style rules:
body {background-color: yellow;}
Course Lecturer: Mr. A. A. Kadams 13 |
Page
h1 {color: blue;}
These style rules can be used to tell a browser that the entire body of a web page
is to have a background color of yellow, and the text of every h1 element on that
page is to be displayed in blue.
A collection of style rules is called a style sheet, so the two rules above could
comprise a very simple style sheet for a web document, as prepared by a web
developer. Everything else in this document would be displayed according to
browser defaults, possibly modified by the user adjusting browser settings.

Once you have some style rules, the next question is this: How do you arrange to
have them applied to one (or more) of your web pages? we have the following
options:
1. The external level, which permits you to place all of your styles in a separate
file (which will normally have a .css extension) and link that file to any and all
HTML documents to which you wish to have those styles applied. This is the
recommended option and the one we will use.
2. The document level, which permits you to group all your styles, place them
within an HTML style element, and then place this style element and its contents
within the head element of your document. These styles will be applied only to
the document in which they appear, and are sometimes called an embedded
style sheet.
3. The inline level, which permits you to apply a given style directly to a single
HTML element by making the style rule the value of the style attribute of that
HTML element. Do not confuse the style element mentioned in the previous
item with the style attribute mentioned here.

Example of the External Level or external style sheet;


<html>
<head>
<title>My webpage</title>
<link rel='stylesheet' type='text/css' href='mystyles.css'>
</head>
<body>
<h1>My Webpage</h1>
<p>Hello World! This is the first paragraph.</p>
<p class='jazzy'>This is the second paragraph.</p>
</body>
</html>

Appearing here is an external style sheet file called ''mystyles.css'' containing all
the styles needed for our HTML:
p {
font-size: 14px;
}
.jazzy {
background-color: red;

Course Lecturer: Mr. A. A. Kadams 14 |


Page
}
h1 {
text-decoration: underline;
color: blue;
}

Example of the Document Level or Internal CSS Style;


<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Browser View Output:

Course Lecturer: Mr. A. A. Kadams 15 |


Page
Example of the Inline Level CSS Style;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 style="color:blue;">A Blue Heading</h1>
<p style="color:red;">A red paragraph.</p>
</body>
</html>

STUDY WORK:
▪ Explain how to use the CSS class and id Selectors.
▪ What are the importance of having comments in CSS?
▪ How do we use CSS to make a website responsive?

JAVASCRIPT (CLIENT-SIDE)
Programming Fundamentals:
JavaScript, originally called LiveScript, was developed by Brendan Eich at
Netscape in 1995 and was shipped with Netscape Navigator 2.0 beta releases.
JavaScript programs are used to detect and react to user-initiated events, such as
a mouse going over a link or graphic. They can improve a Web site with
navigational aids, scrolling messages and rollovers, dialog boxes, dynamic
images, shopping carts, and so forth.

Client-side JavaScript programs are embedded in an HTML document between


HTML head tags <head> and </head> or between the body tags <body> and
</body>. Many developers prefer to put JavaScript code within the <head> tags,
and at times, as you will see later, it is the best place to store function definitions
and objects. If you want text displayed at a specific spot in the document, you may
want to place the JavaScript code within the <body> tags. Or you may have
multiple scripts within a page, and place the JavaScript code within both the
<head> and <body> tags. In either case, a JavaScript program starts with a
<script> tag, and and ends with a </script> tag. And if the JavaScript code is going
to be long and involved, or may be reused, it can be placed in an external file
(ending in .js) and loaded into the page.

Advantages of JavaScript
The merits of using JavaScript are:

Course Lecturer: Mr. A. A. Kadams 16 |


Page
• Less server interaction: You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your
server.
• Immediate feedback to the visitors: They don't have to wait for a page reload
to see if they have forgotten to enter something.
• Increased interactivity: You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces: You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:
▪ Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
▪ JavaScript cannot be used for networking applications because there is no
such support available.
▪ JavaScript doesn't have any multithreading or multiprocessor capabilities.
Once again, JavaScript is a lightweight, interpreted programming language that
allows you to build interactivity into otherwise static HTML pages.

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>


<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML =


"Hello JavaScript!"'>Click Me!</button>

</body>
</html>

<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

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

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
Course Lecturer: Mr. A. A. Kadams 17 |
Page
}
</script>

</body>
</html>

Placement of JavaScript Codes


There is a flexibility given to include JavaScript code anywhere in an HTML
document. However the most preferred ways to include JavaScript in an HTML file
are as follows:
1. Script in <head>...</head> section.
2. Script in <body>...</body> section.
3. Script in <body>...</body> and <head>...</head> sections.
4. Script in an external file and then include in <head>...</head> section.

Example of Script in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

Example of Script in <body>...</body> section


If you need a script to run as the page loads so that the script generates content in
the page, then the script goes in the <body> portion of the document. In this case,
you would not have any function defined using JavaScript. Take a look at the
following code.
<html>
<head>
</head>
<body>
Course Lecturer: Mr. A. A. Kadams 18 |
Page
<script type="text/javascript">
<!--
document.getElementById("output").textContent = "Hello World";
//-->
</script>
<p>This is web page body </p>
</body>
</html>

Example of JavaScript in <body> and <head> Sections


<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.getElementById("output").textContent = "Hello World";
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

Example of JavaScript in External File


As you begin to work more extensively with JavaScript, you will be likely to find that
there are cases where you are reusing identical JavaScript code on multiple pages
of a site.
<html>
<head>
<script type="text/javascript" src=" filename.js" ></script>
</head>
<body>
</body>
</html>

Now, you can keep the following content in filename.js file and then you can use
sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}

JAVASCRIPT CONTROL STATEMENTS (CONDITIONS)

Course Lecturer: Mr. A. A. Kadams 19 |


Page
JavaScript Datatypes: JavaScript Variables:
works with three primitive data types: you must declare it with (var) Keyword:
• Numbers, e.g., 123, 120.50 etc. <script type="text/javascript">
• Strings of text, e.g. "This text string" etc. <!--
• Boolean, e.g. true or false. var money; amount;
money = 2000.50;
In addition to the three core data types,
there are two other special types that var name = "Ali";
consist of a single value: var name;
• null //-->
• undefined </script>

JavaScript Operators:
JavaScript supports the following types;
• Arithmetic Operators e.g. (+, -, /, *, %, ++, --)
document.write("a + b = ");
result = a + b;
document.write(result);
• Comparison Operators e.g. (==, !=, >, <, >=, <=)
var a = 10;
var b = 20;
result = (a == b);
document.write(result);
• Logical (or Relational) Operators e.g. (&&, ||, !)
(a && b) => false
(a || b) => true
!(a && b) => true
• Assignment Operators e.g. (=, *=, +=, -=, /=, %=)
C = A + B will assign the value of A + B into C
C += A is equivalent to C = C + A
C *= A is equivalent to C = C * A
C %= A is equivalent to C = C % A
• Conditional (or ternary) Operators e.g. (? :)
If Condition is true? Then value X : Otherwise value Y
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
switch – case statement: e.g.
switch (grade)
{
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");

Course Lecturer: Mr. A. A. Kadams 20 |


Page
if – else Statement: e.g.
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
}else if( book == "maths" ){
document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
document.write("<b>Economics Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}

JAVASCRIPT CONTROL STATEMENTS (LOOPS)


Loops are used to execute a segment of code repeatedly until some condition is
met. JavaScript's basic looping constructs are;
• while
• for
• do/while

The while Loop: e.g. The do/while Loop: e.g.

<html> <html>
<head> <head>
<title>Looping Constructs</title> <title>Looping Constructs</title>
</head> </head>
<body> <body>
<h2>While Loop</h2> <h2>Do While Loop</h2>
<script language="JavaScript"> <script language="JavaScript">
document.write("<font size='+2'>"); document.write("<font size='+2'>");
let i = 0; // Initialize loop counter vari=0;
while ( i < 10 ){ // Test do{
document.writeln(i); document.writeln(i);
i++; // Increment the counter i++;
} // End of loop block } while ( i< 10 )
</script> </script>
</body> </body>
</html> </html>
The for Loop: e.g.

<html>
<head>
<title>Looping Constructs</title>
</head>
<body>
<h2>For Loop</h2>
<script language="JavaScript">
document.write("<font size='+2'>");
for(vari = 0; i< 10; i++ ){
document.writeln(i);

Course Lecturer: Mr. A. A. Kadams 21 |


Page
}
</script>
</body>
</html>

Try… Catch and Throw statements:


Catching errors in JavaScript:
It is very important that the errors thrown must be catched or trapped so that they
can be handled more efficiently and conveniently and the users can move better
through the web page.
Using try…catch statement:
The try..catch statement has two blocks in it:
• try block
• catch block
The concept of try…catch statement shown in an example:
<html>
<head>
<script type="text/javascript">
try
{
document.write(junkVariable)
}
catch(err)
{
document.write(err.message + "<br/>")
}
</script>
</head>
<body>
</body>
</html>

The output of the above program is ‘junkVariable’ is undefined


throw in JavaScript:
There is another statement called throw available in JavaScript that can be used
along with try…catch statements to throw exceptions and thereby helps in
generating. General syntax of this throw statement is as follows:
throw(exception)
exception can be any variable of type integer or boolean or string.
for example:
<html>
Course Lecturer: Mr. A. A. Kadams 22 |
Page
<head>
<script type="text/javascript">
try
{
varexfor=10
if(exfor!=20)
{
throw "PlaceError"
}
}
catch(err)
{
if(err == "PlaceError")
document.write ("Example to illustrate Throw
Statement: Variable exfor not equal to 20.
<br/>")
}
</script>
</head>
<body>
</body>
</html>

NOTE: Open Chrome, press Ctrl+Shift+j and it opens the JavaScript console
where you can write and test your code.

Popup boxes:
JavaScript uses dialog boxes to interact with the user. The dialog boxes are
created with three methods:
• alert()
• prompt()
• confirm()
The alert() Method
<html>
<head><title>Dialog Box</title></head>
<body bgcolor="yellow" text="blue">
<b>Testing the alert method</b><br>
<script language="JavaScript">
document.write("<font size='+2'>");
document.write("It's a bird, ");
document.write("It's a plane, <br>");
alert("It's Superman!");
</script>
Course Lecturer: Mr. A. A. Kadams 23 |
Page
</body></html>

The Prompt Box


Since JavaScript does not provide a simple method for accepting user input, the
prompt dialog box and HTML forms are used. The prompt dialog box pops up with
a simple text field box. After the user enters text into the prompt dialog box, its
value is returned.
FORMAT
prompt(message);
prompt(message, defaultText);
Example:
prompt("What is your name? ", "");
prompt("Where is your name? ", name);

The Confirm Box


The confirm dialog box is used to confirm a user's answer to a question. A question
mark will appear in the box with an OK button and a Cancel button. If the user
presses the OK button, true is returned; if he presses the Cancel button, false is
returned. This method takes only one argument, the question you will ask the user.
Example
<html>
<head>
<title>Using the JavaScript confirm box</title>
</head>
<body>
<script language = "JavaScript">
document.clear // Clears the page
if(confirm("Are you really OK?") == true){
alert("Then we can proceed!");
}
else{
alert("We'll try when you feel better? ");
}
</script>
</body>
</html>

OBJECTS OF JAVASCRIPT

Course Lecturer: Mr. A. A. Kadams 24 |


Page
Array Objects: Example Date Objects: Example

<html> <html>
<head><title>The Array Object</title> <head><title>Time and Date</title></head>
<h2>An Array of Books</h2> <body bgcolor="lightblue"><h2>Date and
<script language="JavaScript"> Time</h2>
var book = new Array(6); // Create an <script language="JavaScript">
Array object var now = new Date(); // Now is an
book[0] = "War and Peace"; // Assign instance of a Date object
values to its elements document.write("<font size='+1'>");
book[1] = "Huckleberry Finn"; document.write("<b>Local time:</b> " +
book[2] = "The Return of the Native"; now + "<br>");
book[3] = "A Christmas Carol"; var hours=now.getHours();
book[4] = "The Yearling"; var minutes=now.getMinutes();
book[5] = "Exodus"; var seconds=now.getSeconds();
</script> var year=now.getFullYear();
</head> document.write("The full year is " + year
<body bgcolor="lightblue"> +"<br>");
<script language="JavaScript"> document.write("<b>The time is:</b> " +
document.write("<h3>"); hours + ":" + minutes + ":" + seconds);
for(vari in book){ document.write("</font>");
document.write("book[" + i + "] "+ </script>
book[i] + "<br>"); </body>
} </html>
</script>
</body> NOTE: getHours Returns the hour (0–23)
</html> getSeconds Returns the second (0–59)
getFullYear Returns the year with 4 digits)

Math Objects: Example Boolean Objects: Example

<html> var b1 = new Boolean(5);


<head><title>The Math var b2 = new Boolean(null);
Object</title></head>
<body> <script language="JavaScript">
<h2>Math object Methods-- var bool1= new Boolean( 0);
sqrt(),pow()<br> var bool2 = new Boolean(1);
Math object Property--PI</h2> var bool3 = new Boolean("");
<P> var bool4 = new Boolean(null);
<script language="JavaScript"> var bool5 = new Boolean(NaN);
var num = 16; document.write("The value 0 is boolean "+
document.write("<h3>The square root of bool1 +"<br>");
" +num+ " is "); document.write("The value 1 is boolean "+
document.write(Math.sqrt(num),".<br>"); bool2 +"<br>");
document.write("PI is "); document.write("The value of the empty
document.write(Math.PI); string is boolean "+ bool3+ "<br>");
document.write(".<br>"+num+" raised to document.write("The value of null is
the 3rd power is " ); boolean "+ bool4+ "<br>");
document.write(Math.pow(num,3)); document.write("The value of NaN is
document.write(".</h3></font>"); boolean "+ bool5 +"<br>");
</script> </script>
</body></html>

Course Lecturer: Mr. A. A. Kadams 25 |


Page
COMBINATION OF HTML, CSS AND JAVASCRIPT: (EXAMPLE)
<!DOCTYPE html>
<html lang="en">
<head>
<style>
/* Style inputs with type="text", select elements and textareas */
input[type=text], select, textarea {
width: 100%; /* Full width */
padding: 12px; /* Some padding */
border: 1px solid #ccc; /* Gray border */
border-radius: 4px; /* Rounded borders */
box-sizing: border-box; /* Make sure that padding and width stays
in place */
margin-top: 6px; /* Add a top margin */
margin-bottom: 16px; /* Bottom margin */
resize: vertical /* Allow the user to vertically resize the
textarea (not horizontally) */
}

/* Style the submit button with a specific background color etc */


input[type=button] {
background-color: #04AA6D;
color: white;
padding: 12px 40px;
border: none;
border-radius: 8px;
cursor: pointer;
}

/* When moving the mouse over the submit button, add a darker green
color */
input[type=button]:hover {
background-color: #45a049;
}

/* Add a background color and some padding around the form */


.container {
border-radius: 5px;
background-color: #f2f2f2;
padding: 40px;
}
</style>
<meta charset="UTF-8">
<title></title>

</head>
<body>
<div class="container">
<form>

Course Lecturer: Mr. A. A. Kadams 26 |


Page
<label for="fnumber">First Number</label>
<input type="text" name="num1" placeholder="Your First
Number..">

<label for="snumber">Second Number</label>


<input type="text" name="num2" placeholder="Your Second
Number..">

The Sum is: <input type="text" name="sum">


<input type="button" value="Sum" onclick="calcSum()">
</form>
</div>
<script>
function calcSum() {
let num1 = document.getElementsByName("num1")[0].value;
let num2 = document.getElementsByName("num2")[0].value;
let sum = Number(num1) + Number(num2);
document.getElementsByName("sum")[0].value = sum;
}
</script>

</body>
</html>

THE OUTPUT:

Course Lecturer: Mr. A. A. Kadams 27 |


Page
THE W3C DOCUMENT OBJECT MODEL (DOM)
The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a
standard for accessing documents like HTML and XML: is a platform and
language-neutral interface that allows programs and scripts to dynamically access
and update the content, structure, and style of a document."
What is the HTML DOM?
The HTML DOM is:
• A standard object model for HTML
• A standard programming interface for HTML
• Platform- and language-independent
• A W3C standard
With the HTML DOM, JavaScript can access and change all the elements of an
HTML document. The HTML DOM defines the objects and properties of all HTML
elements, and the methods (interface) to access them.
In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
DOM Nodes
According to the DOM, everything in an HTML document is a node.
The DOM says:

Course Lecturer: Mr. A. A. Kadams 28 |


Page
· The entire document is a document node
· Every HTML element is an element node
· The text in the HTML elements are text nodes
· Every HTML attribute is an attribute node
· Comments are comment nodes

Text is Always Stored in Text Nodes


A common error in DOM processing is to expect an element node to contain text.
However, the text of an element node is stored in a text node.
In this example: <title>DOM Tutorial</title>, the element node <title>, holds
a text node with the value "DOM Tutorial".
"DOM Tutorial" is not the value of the <title> element!

The HTML DOM Node Tree


The HTML DOM views an HTML document as a tree-structure. The tree structure
is called a node-tree. All nodes can be accessed through the tree. Their contents
can be modified or deleted, and new elements can be created. The node tree below
shows the set of nodes, and the connections between them. The tree starts at the
root node and branches out to the text nodes at the lowest level of the tree:

The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create dynamic
HTML:

Course Lecturer: Mr. A. A. Kadams 29 |


Page
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or
change.

Inner HTML
The most useful property of our web page objects that we can access is not a part
of the official standard at all. The innerHTML property was introduced by Microsoft
in Internet Explorer as a convenient way of being able to access the entire content
of the HTML container all at once. It turned out to be so convenient that all of the
other browsers quickly added support for this property.
We can use inner HTML either to retrieve the current content of the container or to
insert new content into that container. Let's look at some examples. Here are a
couple of div containers that we might have in our HTML.
<div id="first">
<p>Some text.</p>
<p>Some more text.</p></div>
<div id="second"></div>
The first of our example divs displays two paragraphs of text on the page while the
second displays nothing on the page and is simply a placeholder. We can retrieve
the content of the first div like this:
var content = document.getElementById('first') innerHTML;

The variable content now contains all of the text from the two paragraphs as well
as the paragraph tags themselves. We can now replace those paragraphs
completely by assigning a new value.
Dynamic HTML, or DHTML, is for a collection of technologies used together to
create interactive and animated by using a combination of a static markup
language (such as HTML), a client-side scripting language (such as JavaScript), a
presentation definition language (such as CSS), and the Document Object Model.
DHTML allows scripting languages to change variables in a web page's definition
language, which in turn affects the look and function of otherwise "static" HTML
page content, after the page has been fully loaded and during the viewing process.
Course Lecturer: Mr. A. A. Kadams 30 |
Page
Thus the dynamic characteristic of DHTML is the way it functions while a page is
viewed, not in its ability to generate a unique page with each page load.
By contrast, a dynamic web page is a broader concept — any web page generated
differently for each user, load occurrence, or specific variable values. This includes
pages created by client-side scripting, and ones created by server-side scripting
(such as PHP, Perl, JSP or ASP.NET) where the web server generates content
before sending it to the client.
Uses
DHTML allows authors to add effects to their pages that are otherwise difficult to
achieve. For example, DHTML allows the page author to:
• Animate text and images in their document, independently moving each
element from any starting point to any ending point, following a predetermined
path or one chosen by the user.
• Embed a ticker that automatically refreshes its content with the latest news,
stock quotes, or other data.
• Use a form to capture user input, and then process and respond to that data
without having to send data back to the server.
• Include rollover buttons or drop-down menus.
DHTML FORMS
• Forms are key components of all Web-based applications. But important as
they are, Web developers often present users with forms that are difficult to
use. There are three common problems:
• Forms can be too long. A seemingly endless list of questions is sure to make
the user click the back button or jump to another site.
• In many situations a specific user will need to fill out only some of the form
elements. If you present needless questions to a user, you’ll add clutter to your
page and encourage the user to go elsewhere.
• Form entries often need to conform to certain formats and instructions. Adding
this information to a Web page can make for a cluttered and unappealing
screen.
Choosing The Form You Want
A long form can be shortened in a number of ways. If you have multiple versions
of a form, the chief task becomes pointing people to the right form. Often, a simple
set of links will do: “click here for the simple form, click here for the more
complicated one.” Alternatively, a single page can show one of several forms that
the visitor can choose between using radio buttons.
This approach uses Dynamic HTML (DHTML), which has several benefits. First,
DHTML allows for more flexible formatting. You can apply background images,
borders, fonts, and all the other features you’ve learned to expect from HTML and

Course Lecturer: Mr. A. A. Kadams 31 |


Page
Cascading Style Sheets to DHTML objects. Second, if someone fills out one form,
switches to another, then switches back, there’s a good chance that the browser
will lose the information that was initially entered. This problem doesn’t exist in the
DHTML solution. Third, with DHTML you can do tricky things like clipping and
moving the form around the page.
What is the XML DOM?
Note: XML is a software- and hardware-independent tool for storing and
transporting data. XML and HTML were designed with different goals: XML was
designed to carry data - with focus on what data is, HTML was designed to display
data - with focus on how data looks, XML tags are not predefined like HTML tags
are.
Example of XML
XML: OUTPUT:
<note> Note
<to>Gift</to>
To: Gift
<from>Babangida</from>
<heading>Reminder</heading>
From: Babangida
<body>Don't forget me today!</body> Reminder
</note> Don't forget me today!

The XML DOM is:


• A standard object model for XML
• A standard programming interface for XML
• Platform- and language-independent
• A W3C standard
The XML DOM defines the objects and properties of all XML elements, and the
methods (interface) to access them. In other words: The XML DOM is a standard
for how to get, change, add, or delete XML elements.
DOM Nodes
According to the DOM, everything in an XML document is a node. The DOM says:
• The entire document is a document node
• Every XML element is an element node
• The text in the XML elements are text nodes
• Every attribute is an attribute node
• Comments are comment nodes

DOM Example:

Course Lecturer: Mr. A. A. Kadams 32 |


Page
<?xml version="1.0" encoding="UTF-8"?> <book category="WEB">
<title lang="en">Learn XML</title>
<bookstore> <author>Erik T. Ray</author>
<year>2003</year>
<book category="COOKING"> <price>39.95</price>
<title lang="en">Everyday Italian</title> </book>
<author>Giada De Laurentiis</author>
<year>2005</year> </bookstore>
<price>30.00</price>
</book>

<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

Text is Always Stored in Text Nodes


A common error in DOM processing is to expect an element node to contain text.
However, the text of an element node is stored in a text node.
In this example: <year>2005</year>, the element node <year>, holds a text
node with the value "2005".
"2005" is not the value of the <year> element!
The XML DOM Node Tree
The XML DOM views an XML document as a tree-structure. The tree structure is
called node-tree. All nodes can be accessed through the tree. Their contents can
be modified or deleted, and new elements can be created. The node tree shows
the set of nodes, and the connections between them. The tree starts at the root
node and branches out to the text nodes at the lowest level of the tree:

Course Lecturer: Mr. A. A. Kadams 33 |


Page
JavaScript Object Notation (JSON)
What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent *
The JSON format is syntactically similar to the code for creating JavaScript objects.
Because of this, a JavaScript program can easily convert JSON data into
JavaScript objects. Since the format is text only, JSON data can easily be sent
between computers, and used by any programming language. JavaScript has a
built-in function for converting JSON strings into JavaScript objects:
JSON.parse()
JavaScript also has a built-in function for converting an object into a JSON string:
JSON.stringify()
Example of JSON
{
"student": [
{
"id":"01",
"name": "Tom",
"lastname": "Price"
},

{
"id":"02",
"name": "Nick",
"lastname": "Thameson"
Course Lecturer: Mr. A. A. Kadams 34 |
Page
}
]
}

JSON makes it possible to store JavaScript objects as text.

JSON vs XML
Both JSON and XML can be used to receive data from a web server. The following
JSON and XML examples both define an employee’s object, with an array of 3
employees:

JSON Example
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}

XML Example
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

JSON is Like XML Because


• Both JSON and XML are "self-describing" (human readable)
• Both JSON and XML are hierarchical (values within values)
• Both JSON and XML can be parsed and used by lots of programming
languages
• Both JSON and XML can be fetched with an XMLHttpRequest
Table 4: JSON vs XML: Comparison of Syntax, Performance, and Usability
Feature JSON XML
Syntax Simplicity Easy to read/write Verbose
Data Structure Supports arrays Does not support arrays directly
Support
Readability Shorter and cleaner More tags and structure
Data Parsing JSON.parse() Requires XML parser
Use Case Fast AJAX calls, modern APIs Legacy systems, document structure

Course Lecturer: Mr. A. A. Kadams 35 |


Page
JSON is Unlike XML Because
• JSON doesn't use end tag
• JSON is shorter
• JSON is quicker to read and write
• JSON can use arrays
The biggest difference is:
XML has to be parsed with an XML parser. JSON can be parsed by a standard
JavaScript function.
Why JSON is Better Than XML
• XML is much more difficult to parse than JSON.
• JSON is parsed into a ready-to-use JavaScript object.
• For AJAX applications, JSON is faster and easier than XML:
o Using XML
▪ Fetch an XML document
▪ Use the XML DOM to loop through the document
▪ Extract values and store in variables
o Using JSON
▪ Fetch a JSON string
▪ JSON.Parse the JSON string

Asynchronous JavaScript And XML (AJAX)


AJAX is a developer's dream, because you can:
o Read data from a web server - after the page has loaded
o Update a web page without reloading the page
o Send data to a web server - in the background

AJAX Example
Let AJAX change this text
Change Content

HTML Page
<!DOCTYPE html>
<html>
<body>

<div id="demo">

Course Lecturer: Mr. A. A. Kadams 36 |


Page
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

</body>
</html>

➢ The HTML page contains a <div> section and a <button>.


➢ The <div> section is used to display information from a server.
➢ The <button> calls a function (if it is clicked).
➢ The function requests data from a web server and displays it:

Function loadDoc()
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}

What is AJAX?
➢ AJAX = Asynchronous JavaScript And XML.
➢ AJAX is not a programming language.
➢ AJAX just uses a combination of:
o A browser built-in XMLHttpRequest object (to request data from a
webserver)
o JavaScript and HTML DOM (to display or use the data)

AJAX is a misleading name. AJAX applications might use XML to transport


data, but it is equally common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging data


with a web server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the whole page.

How AJAX Works

Course Lecturer: Mr. A. A. Kadams 37 |


Page
1. An event occurs in a web page (the page is loaded; a button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

NOTE: Modern Browsers can use Fetch API instead of the XMLHttpRequest
Object. The Fetch API interface allows web browser to make HTTP requests to
web servers. If you use the XMLHttpRequest Object, Fetch can do the same in a
simpler way.

WEB APIs
A Web APIs is a developer's dream:

• It can extend the functionality of the browser


• It can greatly simplify complex functions
• It can provide easy syntax to complex code

What is Web API?

• API stands for Application Programming Interface.


• A Web API is an application programming interface for the Web.
• A Browser API can extend the functionality of a web browser.
• A Server API can extend the functionality of a web server.

Browser APIs

Course Lecturer: Mr. A. A. Kadams 38 |


Page
• All browsers have a set of built-in Web APIs to support complex
operations, and to help accessing data.
• For example, the Geolocation API can return the coordinates of where
the browser is located.

Example
Get the latitude and longitude of the user's position:

const myElement = document.getElementById("demo");

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
myElement.innerHTML = "Geolocation is not supported by this
browser.";
}
}

function showPosition(position) {
myElement.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}

Third Party APIs

Third party APIs are not built into your browser. To use these APIs, you will have
to download the code from the Web.

Examples:

• YouTube API - Allows you to display videos on a web site.


• Twitter API - Allows you to display Tweets on a web site.
• Facebook API - Allows you to display Facebook info on a web site.

PHP: SERVER-SIDE PREPROCESSING


The client-side JavaScript programming that we looked at in the previous two
chapters is limited to computing that can be safely executed within the confines of
the browser. These limitations aside, client-side computing has certain
advantages. For example, it limits the amount of data transfer by taking care of
simple computing requests on the client computer, instead of transmitting those
computational requests to the server, having the server perform them, and then
sending the results back to the client. This relieves the server from servicing a large
number of requests for minor computational tasks and cuts down on bandwidth
consumption as well. Equally important is that client-side computing is very useful
Course Lecturer: Mr. A. A. Kadams 39 |
Page
for filtering out potentially malicious data, or simply malformed data, on its way to
the server.
However, client-side computing using JavaScript is not up to the task of performing
much of the computation that is necessary on the contemporary web. Our websites
need to serve dynamically created web pages based on the data from users’ input
devices, files on both the client and server computers, and information contained
in databases stored on servers. In general, for the sake of efficiency, it is better to
have calculations on data performed wherever the data lives, so clearly you will
want to do some serious computing on the server side as well.
Four of the most popular technologies for providing server-side computing are
Active Server Pages (ASP), Java Server Pages (JSP), Perl, and Personal
Home Page (PHP). The use of ASP requires a relatively intensive study of
languages such as Visual Basic, C#, or C++ on Microsoft’s .NET platform. A study
of JSP requires a reasonable prior exposure to the Java programming language.
On the other hand, Perl and PHP are both interpreted scripting languages that, by
comparison, are much easier to learn, especially for those with no prior
programming experience. These languages make it possible for you to get onto
the server side of the web programming highway relatively quickly.
PHP is the easier to learn and use, and is currently the one in wider use. So, it is
our language of choice.
PHP Script Structure and General Syntax:
A Simple First Example:

A very short PHP script embedded in the body of an HTML document. The script
places a Welcome message, with the current date and time, into the markup, on
the server, before the page is sent to the browser for display.

Course Lecturer: Mr. A. A. Kadams 40 |


Page
NOTE: PHP files can contain text, HTML, CSS, JavaScript, and PHP code. PHP
code is executed on the server, and the result is returned to the browser as plain
HTML. PHP files have extension ".php".

Example 2: Basic PHP Form Submission


<!-- form.html -->
<form action="submit.php" method="POST">
Name: <input type="text" name="username">
<input type="submit" value="Submit">
</form>

<?php
// submit.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['username']);
echo "Hello, " . $name;
}
?>
Course Lecturer: Mr. A. A. Kadams 41 |
Page
Example 2 above demonstrates how user input from an HTML form can be
captured and processed using PHP on the server side. It uses $_POST to safely
retrieve form data and htmlspecialchars() to prevent XSS vulnerabilities.
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files,
and even Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
o PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
o PHP is compatible with almost all servers used today (Apache, IIS, etc.)
o PHP supports a wide range of databases
o PHP is free. Download it from the official PHP resource: www.php.net
o PHP is easy to learn and runs efficiently on the server side
BASIC PHP SYNTAX
A PHP script can be placed anywhere in the document. A PHP script starts with
<?php and ends with ?>:
<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".


PHP Case Sensitivity
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are not case-sensitive. In the example below, all three echo
statements below are equal and legal:
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

However; all variable names are case-sensitive!

Course Lecturer: Mr. A. A. Kadams 42 |


Page
In the example below; only the first statement will display the value of the $color
variable! This is because $color, $COLOR, and $coLOR are treated as three
different variables:
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

Comments in PHP
A comment in PHP code is a line that is not executed as a part of the program. Its
only purpose is to be read by someone who is looking at the code.
Example: Single-line comments: Example: Multiple-line comments:

<?php <?php
// This is a single-line /*
comment This is a multiple-lines comment
block
# This is also a single-line that spans over multiple
comment lines
?> */
?>

Variables
A variable starts with the $ sign, followed by the name of the variable:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $x + $y;
?>
Rules for PHP variables:
▪ A variable starts with the $ sign, followed by the name of the variable
▪ A variable name must start with a letter or the underscore character
▪ A variable name cannot start with a number
▪ A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
▪ Variable names are case-sensitive ($age and $AGE are two different
variables)

Course Lecturer: Mr. A. A. Kadams 43 |


Page
PHP is a Loosely Typed Language
In the example above, notice that we did not have to tell PHP which data type the
variable is. PHP automatically associates a data type to the variable, depending
on its value. Since the data types are not set in a strict sense, you can do things
like adding a string to an integer without causing an error.

STUDY WORK:
▪ Explain the three different variable scopes in PHP with example code.
▪ Understand the PHP supported data types: String, Integer, Float (floating
point numbers - also called double), Boolean, Array, Object, NULL, Resource.

PHP echo and print Statements


echo and print are more or less the same. They are both used to output data to
the screen. The differences are small: echo has no return value while print has a
return value of 1 so it can be used in expressions. echo can take multiple
parameters (although such usage is rare) while print can take one argument. echo
is marginally faster than print.

PHP Math
PHP has a set of math functions that allows you to perform mathematical tasks on
numbers.
<?php
echo(pi()); // returns 3.1415926535898
echo(min(0, 150, 30, 20, -8, -200)); // returns -200
echo(max(0, 150, 30, 20, -8, -200)); // returns 150
echo(sqrt(64)); // returns 8
echo(round(0.60)); // returns 1
echo(round(0.49)); // returns 0
echo(rand(10, 100)); //returns random integer between 10 and 100
(inclusive)
?>

PHP OPERATORS
Operators are used to perform operations on variables and values. PHP divides
the operators in the following groups:
▪ Arithmetic operators
▪ Assignment operators
▪ Comparison operators
▪ Increment/Decrement operators

Course Lecturer: Mr. A. A. Kadams 44 |


Page
▪ Logical operators
▪ String operators
▪ Array operators
▪ Conditional assignment operators

PHP Arithmetic Operators


The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power

PHP Assignment Operators


The PHP assignment operators are used with numeric values to write a value to a
variable. The basic assignment operator in PHP is "=". It means that the left
operand gets set to the value of the assignment expression on the right
Assignment Same as... Description
x=y x=y The left operand gets set to the value of the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus

PHP Comparison Operators


The PHP comparison operators are used to compare two values (number or
string): PHP assignment.
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they
are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or
they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal
to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to
$y

Course Lecturer: Mr. A. A. Kadams 45 |


Page
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or
greater than zero, depending on if $x is
less than, equal to, or greater than $y.
Introduced in PHP 7.

PHP Increment / Decrement Operators


The PHP increment operators are used to increment a variable's value and the
PHP decrement operators are used to decrement a variable's value.
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators


The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP Conditional Statements


When you want to perform different actions for different conditions. You can use
conditional statements to do this. In PHP we have the following conditional
statements:
• if statement - executes some code if one condition is true
• if...else statement - executes some code if a condition is true and another
code if that condition is false
• if...elseif...else statement - executes different codes for more than two
conditions
• switch statement - selects one of many blocks of code to be executed.
Example: if statement: Example: if...else statement:
<?php <?php
$t = date("H"); $t = date("H");

if ($t < "20") { if ($t < "20") {


echo "Have a good day!"; echo "Have a good day!";
} } else {
?> echo "Have a good night!";
}
?>
Course Lecturer: Mr. A. A. Kadams 46 |
Page
Example: if...elseif...else Example: switch statement:
statement:
<?php
<?php $favcolor = "red";
$t = date("H");
switch ($favcolor) {
if ($t < "10") { case "red":
echo "Have a good morning!"; echo "Your favorite color is
} elseif ($t < "20") { red!";
echo "Have a good day!"; break;
} else { case "blue":
echo "Have a good night!"; echo "Your favorite color is
} blue!";
?> break;
case "green":
echo "Your favorite color is
green!";
break;
default:
echo "Your favorite color is
neither red, blue, nor green!";
}
?>

PHP Loops
When you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script,
we can use loops. Loops are used to execute the same block of code again and
again, as long as a certain condition is true.
In PHP, we have the following loop types:
• while - loops through a block of code as long as the specified condition is
true
• do...while - loops through a block of code once, and then repeats the loop
as long as the specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
Example: while Loop: Example: do...while Loop:

<?php <?php
$x = 1; $x = 1;

while($x <= 5) { do {
echo "The number is: $x echo "The number is: $x <br>";
<br>"; $x++;
$x++; } while ($x <= 5);
} ?>
?>

Course Lecturer: Mr. A. A. Kadams 47 |


Page
Example: for Loop: Example: foreach Loop:

<?php <?php
for ($x = 0; $x <= 10; $x++) { $colors = array("red", "green",
echo "The number is: $x "blue", "yellow");
<br>";
} foreach ($colors as $value) {
?> echo "$value <br>";
}
?>

PHP FUNCTIONS
A function is a named block of code that performs a specific task. PHP has more
than 1000 built-in functions, and in addition you can create your own custom
functions.

Example: <?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>

PHP ARRAYS
An array is a special variable, which can hold more than one value at a time. An
array can hold many values under a single name, and you can access the values
by referring to an index number.
In PHP, the array() function is used to create an array and there are three types of
arrays:
1. Indexed arrays - Arrays with a numeric index
2. Associative arrays - Arrays with named keys
3. Multidimensional arrays - Arrays containing one or more arrays
Example: Lets get the length of an Array – (The count() Function)
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

PHP Indexed Arrays


There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");

Course Lecturer: Mr. A. A. Kadams 48 |


Page
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Looping through an Indexed Array:
To loop through and print all the values of an indexed array, you could use a for
loop, like this:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

PHP Associative Arrays


These are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Or $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

Looping through an Associative Array:


To loop through and print all the values of an associative array, you could use a
foreach loop, like this:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

PHP Multidimensional Arrays


A multidimensional array is an array containing one or more arrays. In a multi-
dimensional array each element in the main array can also be an array. And each

Course Lecturer: Mr. A. A. Kadams 49 |


Page
element in the sub-array can be an array, and so on. Values in the multi-
dimensional array are accessed using multiple index.
Example: In this example we create a two-dimensional array to store marks of
three students in three subjects;
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),

"qadir" => array (


"physics" => 30,
"maths" => 32,
"chemistry" => 29
),

"zara" => array (


"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";


echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;


echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
</html>

This will produce the following result: -


Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

Course Lecturer: Mr. A. A. Kadams 50 |


Page
PHP - Sort Functions For Arrays:
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the value
• ksort() - sort associative arrays in ascending order, according to the key
• arsort() - sort associative arrays in descending order, according to the value
• krsort() - sort associative arrays in descending order, according to the key

PHP FORMS
The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit
button:
Example:
<html>
<body>

<form action="welcome.php" method="post">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

When the user fills out the form above and clicks the submit button, the form data
is sent for processing to a PHP file named "welcome.php". The form data is sent
with the HTTP POST method.
To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:
<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>
The output could be something like this:
Welcome John
Your email address is [email protected]
Course Lecturer: Mr. A. A. Kadams 51 |
Page
The same result could also be achieved using the HTTP GET method:
<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

and "welcome_get.php" looks like this:


<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2,
key3 => value3, ...)). This array holds key/value pairs, where keys are the names
of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST
method.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL). GET also has limits on the
amount of information to send. The limitation is about 2000 characters. However,
because the variables are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.
GET may be used for sending non-sensitive data.

Course Lecturer: Mr. A. A. Kadams 52 |


Page
Note: GET should NEVER be used for sending passwords or other sensitive
information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request) and has no
limits on the amount of information to send.
Moreover, POST supports advanced functionality such as support for multi-part
binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to
bookmark the page.

PHP Form Validation


The HTML form we will be working at in these chapters, contains various input
fields: required and optional text fields, radio buttons, and a submit button:

The validation rules for the form above are as follows:


Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one

The Validation below:


<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

Course Lecturer: Mr. A. A. Kadams 53 |


Page
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

The Required Fields:


<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {

Course Lecturer: Mr. A. A. Kadams 54 |


Page
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>

Display the Error Messages


Then in the HTML form, we add a little script after each required field, which
generates the correct error message if needed (that is if the user tries to submit
the form without filling out the required fields):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF
"]);?>">

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


<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">

</form>

The Complete Form Example


To show the values in the input fields after the user hits the submit button, we add
a little PHP script inside the value attribute of the following input fields: name, email,
and website. In the comment textarea field, we put the script between the
<textarea> and </textarea> tags. The little script outputs the value of the $name,
$email, $website, and $comment variables.
Then, we also need to show which radio button that was checked. For this, we
must manipulate the checked attribute (not the value attribute for radio buttons):
Course Lecturer: Mr. A. A. Kadams 55 |
Page
Name: <input type="text" name="name" value="<?php echo $name;?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
Website: <input type="text" name="website" value="<?php echo $website;
?>">
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comme
nt;?></textarea>
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
STUDY WORK:
▪ Understand how to use PHP to validate Name, E-mail and URL in Forms.
▪ Use what you have learnt to validate the values and entries of your calculator
assignment with an error message output wherever possible.

PHP Object Oriented Programming (OOP)


From PHP5, you can write PHP code in an object-oriented style which is faster and
easier to execute. Object-oriented programming has several advantages over
procedural programming: It has the following advantages;
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code
and shorter development time
NOTE: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and place
them at a single place and reuse them instead of repeating it

Define a Class
A class is defined by using the class keyword, followed by the name of the class
and a pair of curly braces ({}). All its properties and methods go inside the braces:
Below we declare a class named Fruit consisting of two properties ($name and
$color) and two methods set_name() and get_name() for setting and getting the
$name property:

Course Lecturer: Mr. A. A. Kadams 56 |


Page
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>

NOTE: In a class, variables are called properties and functions are called methods!
Define Objects
Classes are nothing without objects! We can create multiple objects from a class.
Each object has all the properties and methods defined in the class, but they will
have different property values. Objects of a class is created using the “new”
keyword.
Example;
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}

$apple = new Fruit();


$apple->set_name('Apple');
$apple->set_color('Red');
Course Lecturer: Mr. A. A. Kadams 57 |
Page
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>

Access Modifiers
There are three access modifiers:
• public - the property or method can be accessed from everywhere. This is
default
• protected - the property or method can be accessed within the class and by
classes derived from that class
• private - the property or method can ONLY be accessed within the class
Example Below;
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}

$mango = new Fruit();


$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

Inheritance in OOP
This is when a class derives from another class. The child class will inherit all the
public and protected properties and methods from the parent class. In addition, it
can have its own properties and methods. It is defined by using the “extends”
keyword.
Example:
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
Course Lecturer: Mr. A. A. Kadams 58 |
Page
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
STUDY WORK:
▪ Understand the other principles of OOP such as Abstraction, Polymorphism
and Encapsulation.
▪ Study and when to use Constructor and Destructor in PHP.
▪ Students should try to understand the following: Constants, Abstract Classes,
Interfaces and Namespaces.

DATABASE (MySQL)
PHP can connect to and manipulate databases. MySQL is the most popular
database system used with PHP.
Database Queries
A query is a question or a request. We can query a database for specific
information and have a record set returned. Look at the following query (using
standard SQL):
SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the
"Employees" table.
Connecting to MySQL
To access data in the MySQL database, we need to be able to connect to the
server:
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
Course Lecturer: Mr. A. A. Kadams 59 |
Page
}
echo "Connected successfully";

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";

Course Lecturer: Mr. A. A. Kadams 60 |


Page
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
$conn = null;
?>

STUDY WORK:
▪ Although, MySQL and other DBMS can be managed independently, you are
strongly advised to know how to do the following with MySQL in PHP; Create
Table, Insert Data, CRUD Data and Select Data.

Putting it all together (ASSIGNMENT)


In this web application, you will be expected to use most or parts of the major concepts in
this handout. i.e. HTML, CSS, JavaScript, PHP and MySQL. Additional use of concepts
such as AJAX or OOP attracts more marks.
Simply build a Student Attendance ID Card management system. A student can register,
then login and fill a form that an Admin user can print the Attendance ID Card for the
student to attend a function created by the Admin. Note. The date of registration should
be used to tell how long in days the student has been a member on the ID Card.

Course Lecturer: Mr. A. A. Kadams 61 |


Page

You might also like