0% found this document useful (0 votes)
6 views389 pages

Final Web

Uploaded by

211184
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)
6 views389 pages

Final Web

Uploaded by

211184
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/ 389

INTRODUCTION TO THE

Mohammed Jabari
INTERNET AND WEB

Prepared by: Mohammed Jabary


1
INTERNET

 Itis the largest network in the world that


connects hundreds of thousands of

Mohammed Jabari
individual networks all over the world.
 The popular term for the Internet is the
“information highway”.
 Rather than moving through geographical
space, it moves your ideas and information
through cyberspace – the space of electronic
movement of ideas and information.
2
INTERNET

 No one owns it
 It has no formal management organization.

Mohammed Jabari
 As it was originally developed by the Department of
defense ARPANET - the US department of defence
wanted to develop a computer network that could
withstand nuclear attack. The Internet lack of
centralization made it less vulnerable to wartime or
terrorist attacks.
 To access the Internet, an existing network need to
agree to certain standards based on the TCP/IP
(Transmission Control Protocol/Internet Protocol) .
3
THE USES OF THE INTERNET
 Send e-mail messages.
 Send (upload) or receive (down load) files

Mohammed Jabari
between computers.
 Participate in discussion groups, such as mailing
lists and newsgroups.
 Surfing the web.

 Socializing

 Communication

 Grid Computing

 Cloud Computing.

 P2P application
4
HOW TO ACCESS THE INTERNET?

 Many schools, Universities and businesses


have direct access to the Internet using
special high-speed communication lines and

Mohammed Jabari
equipment.
 Students and employees can access through
the organization’s local area networks
(LAN) or through their own personal
computers.
 Another way to access the Internet is
through Internet Service Provider (ISP).
5
HOW TO ACCESS THE INTERNET?
 To access the Internet, an existing network
need to pay a small registration fee and
agree to certain standards based on the
TCP/IP (Transmission Control

Mohammed Jabari
Protocol/Internet Protocol) reference model.
 Each organization pays for its own networks
and its own telephone bills, but those costs
usually exist independent of the internet.
 The regional Internet companies route and
forward all traffic, and the cost is still only
that of a local telephone call.
6
INTERNET SERVICE PROVIDER (ISP)

A commercial organization with permanent


connection to the Internet that sells

Mohammed Jabari
temporary connections to subscribers.
 Examples:

 Hadara, Madaa.

7
WHAT IS THE WEB
 The Web is one of the many services
available on the Internet.

Mohammed Jabari
 Created by Tim Berners Lee, a researcher
for CERN, in 1990
 Originally to aid researchers find
information through a linked texts
 Used HTTP for protocol and HTML for
content of pages and Web Browsers to
display the content
 Still no images at this point 8
WHAT IS WEB?
 The Web (World Wide Web) consists of
information organized into Web pages
containing text and graphic images.

Mohammed Jabari
 It contains hypertext links, or highlighted
keywords and images that lead to related
information.
 A collection of linked Web pages that has a
common theme or focus is called a Web site.
 The main page that all of the pages on a
particular Web site are organized around and
link back to is called the site’s home page. 9
HOW TO ACCESS THE WEB?

 Once you have your Internet connection, then you need


special software called a browser to access the Web.
 Web browsers are used to connect you to remote

Mohammed Jabari
computers, open and transfer files, display text and
images.
 Web browsers are specialized programs.

 Examples of Web browser: Chrome, Firefox, Safari and


Internet Explorer.

10
CLIENT/SERVER STRUCTURE OF THE WEB

 Web is a collection of files that reside on


computers, called Web servers, that are located

Mohammed Jabari
all over the world and are connected to each other
through the Internet.
 When you use your Internet connection to become
part of the Web, your computer becomes a Web
client in a worldwide client/server network.
 A Web browser is the software that you run on
your computer to make it work as a web client.
11
Mohammed Jabari
12
WEB MAIN COMPONENTS
 The following make the main components of the
web:

Mohammed Jabari
 HTML
 HTTP
 Web Browser.

 All modern Web technologies are based on these


components.

13
HYPERTEXT MARKUP LANGUAGE
(HTML)
 The public files on the web servers are ordinary text
files, much like the files used by word-processing

Mohammed Jabari
software.
 To allow Web browser software to read them, the text
must be formatted according to a generally accepted
standard.
 The standard used on the web is Hypertext markup
language (HTML).

14
HYPERTEXT MARKUP LANGUAGE
(HTML)

 HTML is a descriptive language not a programming


language.
 HTML uses codes, or tags, to tell the Web browser

Mohammed Jabari
software how to display the text contained in the
document.
 For example, a Web browser reading the following line
of text:
<B> A Review of the Book<I>Wind Instruments of
the 18th Century</I></B>
 recognizes the <B> and </B> tags as instructions to
display the entire line of text in bold and the <I> and
</I> tags as instructions to display the text enclosed by
those tags in italics.

15
ADDRESSES ON THE WEB:IP
ADDRESSING
 Each computer on the internet does have a unique
identification number, called an IP (Internet Protocol)
address.
 The IP addressing system currently in use on the

Mohammed Jabari
Internet uses a four-part number.
 Each part of the address is a number ranging from 0 to
255, and each part is separated from the previous part
by period,
 For example, 106.29.242.17

16
DOMAIN NAME ADDRESSING

 Most web browsers do not use the IP address t


locate Web sites and individual pages.
 They use domain name addressing.

Mohammed Jabari
 A domain name is a unique name associated
with a specific IP address by a program that
runs on an Internet host computer.
 This program, which coordinates the IP
addresses and domain names for all computers
attached to it, is called DNS (Domain Name
System ) software.
 The host computer that runs this software is
called a domain name server.
17
DOMAIN NAME ADDRESSING

 Domain names can include any number of parts


separated by periods, however most domain names
currently in use have only three or four parts.
 Domain names follow hierarchical model that you can
follow from top to bottom if you read the name from the

Mohammed Jabari
right to the left.
 For example, the domain name gsb.uchicago.edu is the
computer connected to the Internet at the Graduate
School of Business (gsb), which is an academic unit of
the University of Chicago (uchicago), which is an
educational institution (edu).
 No other computer on the Internet has the same domain
name.
18
UNIFORM RESOURCE LOCATORS
 The IP address and the domain name each identify a
particular computer on the Internet.
 However, they do not indicate where a Web page’s
HTML document resides on that computer.

Mohammed Jabari
 To identify a Web pages exact location, Web browsers
rely on Uniform Resource Locator (URL).
 URL is a four-part addressing scheme that tells the
Web browser:
➢ What transfer protocol to use for transporting the file
➢ The domain name of the computer on which the file
resides
➢ The pathname of the folder or directory on the computer
on which the file resides
➢ The name of the file
19
STRUCTURE OF A UNIFORM RESOURCE
LOCATORS

protocol pathname

Mohammed Jabari
http://www.ppu.edu/students/index.htm

Domain name filename

http => Hypertext Transfer Protocol 20


WHAT IS HTTP?

Mohammed Jabari
 HTTP, the Hypertext Transfer Protocol, is the
application-level protocol that is used to transfer
data on the Web.

 HTTP comprises the rules by which Web


browsers and servers exchange information.
 Two other protocols that you can use on the
Internet are the File Transfer Protocol (FTP) and
the Telnet Protocol
21
HOW DOES HTTP WORK?

 HTTP Is a request-response protocol. For


example, a Web browser initiates a request to a

Mohammed Jabari
server, typically by opening a TCP/IP connection.
 The request itself comprises
 a request line,
 a set of request headers, and
 an entity.

 The server sends a response that comprises


 a status line,
 a set of response headers, and 22
 an entity.
HOW DOES HTTP WORK?

 The entity in the request or response can be

Mohammed Jabari
thought of simply as the payload, which may be
binary data, i.e. image, html/Text
 The other items are readable ASCII characters.

 When the response has been completed, either


the browser or the server may terminate the
TCP/IP connection, or the browser can send
another request.

23
Mohammed Jabari
24
HTTP AN EXAMPLE (THE REQUEST)
 As an illustration of HTTP, suppose that you
have requested the following address using your
firefox browser: http://www.ppu.edu

Mohammed Jabari
 The browser sends the following HTTP request to
www.ppu.edu:
 GET / HTTP/1.1
 Connection: Keep-Alive
 User-Agent: Mozilla/5.0 (compatible; Konqueror/2.2-11; Linux)
 Accept: text/*, image/jpeg, image/png, image/*, */*
 Accept-Encoding: x-gzip, gzip, identity
 Accept-Charset: Any, utf-8, *
 Accept-Language: en, en_US
 Host: www.ppu.edu 25

 -- blank line –
HTTP REQUEST EXPLAINED
 The first line is the request line that comprises three fields:
1. a method: The GET method indicates that the server is
supposed to return an entity.

Mohammed Jabari
2. a request-URI (Universal Resource Identifier). The / indicates
the root of the document system on the server, and
3. HTTP protocol version: 1.1 in this case.
 The second line is the optional Connection header informs the
server that the browser would like to leave the connection open
after the response.
 The third line is the optional User-Agent header that identifies
the kind of browser that is sending the request, its version, and
its operating system.
 The Accept headers specify the type, language, and encoding for
the returned entity that the browser would prefer to receive from
the server. 26
HTTP EXAMPLE (THE RESPONSE)
 Responding to the browser, the www.ppu.edu server sends
the following response:
 HTTP/1.1 200 OK

Mohammed Jabari
 Date: Thu, 24 Jan 2002 17:33:52 GMT
 Server: Apache/1.3.14
 Last-Modified: Mon, 21 Jan 2002 22:08:33 GMT
 Etag: “47bc6-25e0-3c4c9161”
 Accept-Ranges: bytes
 Content-Length: 9696
 Connection: close
 Content-Type: text/html
 -- blank line--
 -- HTML entity --

27
HTTP RESPONSE EXPLAINED
 The first line is the status line consisting of three
fields:

Mohammed Jabari
1. HTTP protocol version of the response: 1.1 in this
case,
2. a three-digit numeric status code, and
3. a short description of the status code.
 The Content-Length, Content-Type, Etag, and
Last-Modified header lines describe the entity
returned.

28
REFERENCES
 www.W3schools.com

Mohammed Jabari
 HTTP/1.1 Specification (http://www.rfc-
editor.org/rfc/rfc2616.txt)

29
Web Technologies

Introduction to Web Technologies (2)

1
IN THIS LECTURE

 Static Web Pages

 Dynamic Web Pages

 Front-end and Back-end Technologies

2
STATIC AND DYNAMIC WEB PAGES
 Two kinds of web pages: static web pages and
dynamic web pages

 Static web pages have static content

 Dynamic web pages have dynamic content

 Web content: is everything that can appear on a


Web page (text, images, hyperlinks, …)

3
STATIC WEB PAGES
 A page whose content consists of some HTML code
and saved as an .htm or .html file

 The page has already completely determined the


exact content of the page, in HTML, at some time
before any user visits the page.
 Called "design-time page construction"

 Appearance of a static web page is always the same


– regardless of who visits the page, or when they
visit, or how they arrive at the page, or any other
factors.

 Costs ?
4
STATIC PAGE EXAMPLE
<hmtl>
<head><title>A Welcome Message</title></head>
<body>
<h1>Welcome</h1>
Welcome to our web site. Please feel free to view
our
<a HREF="contents.htm">list of contents</a>.
<br><br>
If you have any difficulties, you can
<a href="mailto:[email protected]">send e
mail to the webmaster</a>.
</body>
</html> 5
6
HOW ARE STATIC WEB PAGES
SERVED

7
ADVANTAGES OF STATIC WEB
PAGES

 Quick to develop

 Cheap to develop

 Cheap to host

8
THE LIMITATIONS OF STATIC
WEB PAGES
 Let it displays the current time or a special message
that is personalized for each user !!

 HTML offers no features for personalizing your web


pages

 Requires web development expertise to update site

 Maintenance cost

 No security with HTML, the code is there for


everybody to view

 So, what we need is a way to generate the HTML


after the page is requested.
9
WHAT IS A WEB SERVER ?
 A web server is a piece of software that
manages web pages and makes them available to
'client' browsers – via a local network or over the
Internet

 The commonest ones being Apache, IIS and


Iplanet's Enterprise server

10
DYNAMIC WEB PAGES
 Constructed "on the fly" when a page is requested

 Can be maintained directly by the customer.

 Initially costs more to develop

 Created using technologies like ASP, ASP. Net,


PHP, Node, JSP … etc.

11
ADVANTAGES OF DYNAMIC
WEB PAGES
 In comparison to “Static web pages”, the
“Dynamic web pages” are:

 much more functional website

 much easier to update

 new content brings people back to the site

 allow you to change only the content of the website


and not the design, so you will not be able to
accidentally break the visual style of the website
12
DISADVANTAGES OF DYNAMIC
WEBSITES
 When compared to “Static web pages”, the
“Dynamic web pages” are:

 slower

 more expensive to develop

 their hosting is more expensive

13
Web Technologies
 Web Technologies can be classified into two
types:

 Front-end (Client-Side) Web Technologies

 Back-end (Server-Side) Web Technologies

14
Front-end (CLIENT-SIDE) WEB Technologies

 Modules (or plug-ins) attached to the browser do all


the work of creating dynamic pages.

 They take a long time to download

 Client (Browser ) dependent: Different browsers


interpret these instructions in different ways.

 They can’t directly access server-side resources


such as databases

 Scripting is available to everybody, which can be


undesirable. 15
Front-end (CLIENT-SIDE) WEB
Technologies
 Front-end Technologies:
 HTML
 CSS
 JavaScript,
 VBScript,
 ActiveX Controls,
 Java Applets,
 Flash

16
Front-end (CLIENT-SIDE)

17
CLIENT-SIDE TECHNOLOGIES
 JavaScript
 Is the original browser scripting language, and is not Java
 Can control browser behavior and content.
 Most modern Web technologies (Angular, Vue, React)
depends heavily on JavaScript

 CSS
 Used to control the appearance and behavior of HTML
 Separate page structure (HTML) from format.

18
Client-Side Technologies ….

 ActiveX Controls
 Old Technology used by Microsoft
 Is a self-contained program (or component), written in a
language
 added to HTML pages via the <object> tag
 able to manipulate items on the user's machine such as the
files or Windows registry .
 it is considered a security risk and is not even allowed
through firewalls

19
20
CLIENT-SIDE TECHNOLOGIES ….

 Java applets
 use Java code in the form of applets
 inserted into web pages with the aid of the <applet>
tag
 supported via the Java Virtual Machine (JVM )

 Flash

21
Back-end (SERVER-SIDE) WEB Technologies

 Run on the Server Side


 Instructions that are used to generate HTML for
the page at the time the user requests the page
 All the processing is done on the server, before the
page is sent back to the browser

 Only the HTML code of page is actually sent to the


browser
 Technologies: ASP, ASP.Net, PHP, Node, JSP (Java
Server Pages)…etc

22
Back-end (SERVER-SIDE) WEB
Technologies
 Technologies:
 ASP.Net
 PHP
 JSP (Java Server Pages)
 Ruby on Rails
 Node
 CGI

23
Back-end (SERVER-SIDE)

24
HTML
Review: Client and Server

• User uses HTTP client (Web Browser)


• It has a URL (e.g. http://www.yahoo.com/)
• Makes a request to the server
• Server sends back data (the response)
• User clicks on the client side...

request (URL)

Client response (HTML, …) Server


HTML Characteristics

• Just a Text File!


+ Portable
+ Human Readable/Writable
• Defines the Structure (not Appearance) of the Document
• Client (Browser) defines the appearance
• Font preferences, window width, …
• Pours into Browser (PDAs, Bigger/Smaller)
Document Structure

<html>
<head><title>My First Web Page</title>
</head>
<body bgcolor="white">
<p>A Paragraph of Text.</p>
</body>
</html>
Nested Tags

• Like a tree, each element is contained inside a parent


element
• Each element may have any number of attributes

<html>...</html>

<head>...</head> <body>...</body> bgcolor="white"

<title>...</title> other stuff <p>...</p> <br> <table>...</table>

This is some text!


Basic Tags

<html>
<head><title>My First Web Page</title>
</head>
<body bgcolor="white">
<p>A Paragraph of Text.</p>
</body>
</html>
Basic Tags

• <!doctype html public “-//w3c//dtd html 4.0 transitional//en”>


• Preamble which identifies content as HTML
• <h1>…</h1>
• H1-6 where larger number means smaller heading
• <p>
• Includes vertical whitespace unlike <br>
Basic Tags

• <hr> horizontal rule


• <br> new line
• <b>...</b> bold
• <i>...</i> italicize text in between
Lists

• Unordered Lists o Apples


<ul> 1. Fuji
<li> Apples 2. Granny Smith
<li> Oranges o Oranges
</ul>
• Ordered Lists
<ol>
<li> One
<li> Two
</ol>
• Can be nested
Image Files

• <img src="URL of image file">


• JPEG
• Best for photos
• Public standard
• GIF
• Best for simple images
• Older standard
• PNG – Portable Network Graphics
• Public standard replacement for GIF
• SVG – Scalable Vector Graphics
• Series of drawing commands
• Uses XML
Tables

• <table>...</table>
• <tr>...</tr> for each row
• <td>...</td> for each element in a row
• <th>…</th> for header row
Table Example

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Comments

• <!-- This is a comment -->


• <!--
This paragraph,
is also a
comment...
-->
Special HTML

• &lt; → <
• &gt; → >
• &amp; → &
• &nbsp; → space
Anchor Tag (Links)

Absolute HREFs specify fully qualified URLs.

• <a href="http://www.yahoo.com/">Yahoo!</a>
• <a href="reldoc.html">In this directory!</a>
• <a href="a/doc.html">In sub-directory a!</a>

Relative HREFs are relative to the directory containing the


current HTML file.
What is the WWW?

• A hypertext system that runs on top of the Internet, based on Three


Main Standards
• URL
• HTTP
• HTML
Client/Server Timeline

Client Server

(S1) create new socket (socket)


(S2) bind socket to port 80 (bind)
(S3) permit socket connections (listen)
(S4) wait for connection (accept)
(C1) get IP address & port .
(C2) create new socket (socket) .
(C3) connect to server IP:port (connect) .
. .
. .
. .
. (S5) application notified of connection
. (S6) start reading request (read)
. .
(C4) connection successful .
(C5) send HTTP request (write) .
(C6) wait for HTTP response (read) .
. (S7) process HTTP request message
. .
. .
. (S8) send back HTTP response (write)
(C7) process HTTP response (S9) close connection (close)
(C8) close connection (close)
CSS
1 Prepared By: Mohammed Jabary
WHAT IS CSS
 CSS stands for Cascaded Style Sheets
 CSS can save you a lot of time

 CSS is used to control style and layout of


multiple WebPages all at once
 It simply separates design from content

 Styles defines how to display HTML

2
WHY TO USE STYLES?
 Documents written with CSS are Webpage

 more flexible
 short Style-
Structure
formatting
 clear
 Basic formating tool
(X)HTML CSS
 Easy multiple document managment

 Save time by using selector classes

 New opportunities in formating

3
HTML WITH AND WITHOUT CSS

4
LETS SEE SOME CODE
 Rule Structure

5
BASIC SYNTAX
 Made up of three parts:
selector {property: value}
 The selector is normally the HTML element/tag
you wish to define
 The property is the attribute you wish to change

 Every property has the value

6
SYNTAX
 If the value is multiple words, put quotes around
the value
p {font-family: "sans serif"}
 To make the style definitions more readable, you
can describe one property on each line
p
{
text-align: center;
color: black;
font-family: arial
}
7
GROUPING
h1,h2,h3,h4,h5,h6
{
color: green
}
 All header elements will be displayed in green
text color
This is header h1
This is header h2
This is header h3
This is header h4
8
CLASS SELECTOR
 With the class selector you can define different
styles for the same type of HTML element.
p.right {text-align: right}
p.center {text-align: center}
 Using the class argument in (X)HTML:
<p class="right"> This paragraph will be
right-aligned. </p>
<p class="center"> This paragraph will be
center-aligned. </p>

9
CLASS SELECTORS
 Class Selectors

H1.warning {color: red;}


OR to an entire class…
.warning {color:green;}

 In your HTML code -

<H1 CLASS=“warning”>Danger!</H1>
<P CLASS=“warning”>Be careful…</P>
…….
10
ID SELECTOR
 The Id selector uses the id attribute of an HTML
element to apply a rule
 The Id of an element must be unique in the
entire page
 The id selector is defind using the “#” symbol

#para1 {
text-align: center;
color: red;
}

<p id=‘para1’ > Hello World </p>


11
CONTEXTUAL SELECTORS
 Contextual – (refer to HTML, but in context)
LI B {color: purple;}

The above rule is applied to all <B> elements in a <Li>


elements only

12
REFERRING TO MORE THAN ONE CLASS
 HTML elements can refer to more than one class
 Suppose we have the following CSS rules:

p.center {
text-align: center;
color: red; }

p.large {
font-size: 300%; }

 The following <p> element refers to both classes

<p class="center large">This paragraph will be red, center-


aligned, and in a large font-size.</p>
13
EXTERNAL STYLE SHEET
 Each webpage must link to the style sheet
using the <link> tag

 Browser reads styles definitions from mystyle.css file

<head>
<link rel="stylesheet" type="text/css"
href="mystyle.css" />
</head>
14
INTERNAL STYLE SHEET
 Should be used when a single document has a unique
style

 Defined in the head section by using the <style> tag

<head>
<style>
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}
</style>
</head> 15
INLINE STYLE
 The CSS style is written inside in the HTML tags
 It has the highest priority
 It’s not recommended as violates the separation
between content and style best practice

<body>

<h1 style=“color:red ; text-size:18”> Welcome </h1>

</body>

16
CASCADING ORDER
1. Inline style
➢ inside an HTML element
2. External or Internal style sheet
➢ External: inside external *.css file Internal style sheet
➢ Internal: inside the <head> tag using the <style> tag
3. Browser default

The highest priority is the Inline followed by the External or


the Internal depending on the order of appearance.

17
MULTIPLE STYLE SHEETS
 An internal style sheet  What will be the format
has following properties of <h3> tag? Suppose the
for the h3 selector: External css link
h3 { text-align: right; appears before the
font-size: 20pt } Internal Style
 External style sheet has
these: o color: red;
h3 { color: red; o text-align: right;
text-align: left; o font-size: 20pt
font-size: 8pt }
 Your Web Browser has
default formatting:
h3 { color: black;
font size: 10pt }
18
CSS EXAMPLES

19
BACKGROUND:
 Control over the  background-color
background color of an  color-rgb
element color-hex
color-name
 set an image as the
background,  background-image
 url(URL)
 repeat a background none
image
 background-repeat
 repeat
repeat-x
repeat-y
no-repeat

20
21
TEXT:
 color  text-decoration
 direction  none
 ltr underline
rtl overline
line-through
 word spacing blink
 normal  text-align
length
 left
right
center
justify

22
23
FONT:
 font-family  font-weigh
• family-name  normal
generic-family bold
 font-size bolder
lighter
 xx-small 100
x-small
small
 /etc./

24
{DIMENSION

25
LIST:
<head>
<style type="text/css">
ul
{
list-style-image: url('arrow.gif')
}
</style>
</head>

<body>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</body>

26
THE CSS BOX MODEL
 In CSS, HTML elements are considered boxes
 The CSS box model is essentially a box wrapping
the html elements
 The Box Model consists of:
1. Margin
2. Border
3. Padding
4. The Actual Content

27
THE BOX MODEL

28
THE BOX MODEL
Explanation of the different parts:
 Margin - Clears an area around the border. The
margin does not have a background color, it is
completely transparent
 Border - A border that goes around the padding
and content. The border is affected by the
background color of the box
 Padding - Clears an area around the content. The
padding is affected by the background color of the
box
 Content - The content of the box, where text and
29
images appear
WIDTH AND HEIGHT OF AN ELEMENT

 Important: When you set the width and height


properties of an element with CSS, you just set
the width and height of the content area.
 To calculate the full size of an element, you must
also add the padding, borders and margins.

 The total width of the element in the example


below is 300px:

30
EXAMPLE
 Consider the following CSS style:

width:250px;
padding:10px;
border:5px solid gray;
margin:10px;

 The total width of this element is 300px!


 How?
250px (width)
+ 20px (left and right padding)
+ 10px (left and right border)
+ 20px (left and right margin)
31
= 300px
BOX MODEL AND CSS BOX-SIZING
PROPERTY

 box-sizing is new property introduced in CSS.


 box-sizing, if set to “border-box” means the
width and height attributes of the element must
include padding and border.
 Example:
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;

The Total width of this element is 300, the total


height is 100. 32
WEBPAGE NORMAL FLOW
 Normal flow is the way that elements are
displayed in a web page
 All elements in HTML are inside boxes which
are either block boxes or inline boxes.

33
BLOCK BOXES
 Block boxes are positioned on a page one after
the other (in the order they're written in the
HTML).
 They start in the upper left of the containing box
and stack from top to bottom. The distance
between each box is defined by the margins with
top and bottom margins collapsing into one
another.
 All block level elements inherit the width of their
parent element by default.

34
BLOCK BOXES EXAMPLE
In the HTML
<div> hello this is a div </div>
<div> another div, notice how it’s stacked below </div>
<div> another div. </div>

This is how it will look like in a browser


hello this is a div
another div, notice how it’s stacked below
another div.

Each DIV is a block element, so it will be placed


below the previous block element. Each left outer
edge will touch the left edge of the containing
block. 35
INLINE BOXES
 Inline boxes are laid out on the page horizontally,
one after the other beginning at the top of the
container element.
 When there isn't enough space to fit all the
elements of the inline box on one line, they wrap
to the next line and stack vertically from there

36
INLINE BOX EXAMPLE
In the HTML

<p> this is a text <b> this is Bold </b><i> italic </i> another text</p>

This is how it will look like in a browser


this is a text this is Bold italic another text
The paragraph is a block element, but there are 5
inline elements:
 This is a text

 “this is Bold”

 “italic”
37
 Another text
CSS FLOAT PROPERTY
 Normal page flow is how these block and inline
elements will display on the web page without
any intervention by the web designer.
 If you want to affect where an element is on a
page you can use CSS positioning or CSS floats.
 The float CSS property specifies that an element
should be placed along the left or right side of its
container.
 It allows text and inline elements to wrap around
it.
 The element is removed from the normal flow of
the web page, though still remaining a part of the
flow (in contrast to absolute positioning). 38
CSS FLOAT PROPERTY
 Float CSS property is a very important property for layout.
 It allows you to position your web page designs exactly as
you want them to display—but in order to use it you have
to understand how it works.
 In a style sheet, the CSS float property looks like this:

.right { float: right; }

 This tells the browser that everything with the class of


“right” should be floated to the right.

 In HTML, you would assign it like this:

39
class="right" />
CSS FLOAT PROPERTY
 You can’t float every element on a web page. You
can only float block-boxes elements.
 These are the elements that take up a block of
space on the page, like images <img>,
paragraphs <p>, divisions <div>, and lists <li>.

 Other elements that affect text, but don’t create a


box on the page are called inline elements and
can’t be floated. These are elements like span
<span>, line breaks <br>, strong emphasis
<b><strong>, or italics <i>.
40
CSS CLEAR PROPERTY
 Clears elements around the cleared element
 Can take the following values

clear: both; clears both sides of the element


clear: left; clears left side of the element
clear: right; clears right side of the element
clear: none; default value
clear: inherit; inherit the clear value of its parent

41
HTML LAYOUTS
 In HTML you can create websites layouts using
either:
 <div> which is a block element
 <Tables> by specifying number of columns and rows

See Example at the elearrning.

42
CREATING LAYOUT USING DIV ELEMENTS
 See the provided example for a layout to use with
your project

43
CSS ISN’T PERFECT (YET)
 CSS support in browsers is still uneven
 Make sure your CSS properties are supported

44
CSS AND BROWSER COMPATIBILITY

45
REFERENCES
 http://www.w3schools.com/css/
 Learn CSS
 http://validator.w3.org/
 Check Your CSS syntax
 http://www.csszengarden.com/
 The beauty of CSS Design
 One HTML file
 210 CSS

 https://www.thoughtco.com/normal-flow-definition-
3467023

46
XP

JavaScript

Bringing life to a web page

1
XP
JavaScript is Popular

 Programming
languages popularity
according to
Stackoverflow survey
2018

 Source:
https://insights.stackove
rflow.com/survey/2018/

2
XP
JavaScript Evolution
 JavaScript which started as small project
is now one of the most used programming
languages ever.
 The whole Web, client and server, relies
heavily on programs written in JavaScript.
 Mobile Apps are now developed using
JavaScript.
 Many JavaScript programming
Frameworks and libraries have evolved
over the time.
3
XP
JavaScript
 Examples of JavaScript Libraries and
Frameworks:
◦ AngularJS, Angular, React, React Native,
jQuery, and many others.
 JavaScript is not a Strongly Typed
language, i.e. it’s not like C/C++ and Java
which requires the programmer to declare
and define each variable.

4
XP
JavaScript
 JavaScript syntax is sometimes difficult to
debug and complex to write when it comes
to big programs
 But because of its popularity -all browsers
today supports JavaScript -programmers
needs to deal with it.
 Many programming languages have evolved
to make writing JavaScript programs easier,
these programming languages are Transpiled
(converted ) to JavaScript programs

5
XP
JavaScript
 Transpilation Actually allows developers
to code in another language and auto-
converting it “under the hood” to
JavaScript.
 Example of these languages:
◦ TypeScript
◦ CoffeeScript
◦ Dart

6
JavaScript for Client-Side XP
Programs
 Solves many of the problems associated with
server-side scripts
 Can be tested locally without first uploading it
to a Web server, you only need a Browser.
 Are likely to be more responsive to the user
 Can never completely replace server-side scripts
 Usually, JavaScript programs running on the
Browser interact with server-side programs run
on the server.

7
XP
Introduction to JavaScript
 JavaScript is an interpreted programming
or script language
 JavaScript run inside the browser.
 Also, JavaScript has special runtime to run
on a server, e.g. Node.
 JavaScript is not Java, both are different
and not related.

8
XP
Introduction to JavaScript
 In this part of the course we will talk
about JavaScript as a client-side
technology (front-end).
 JavaScript was created to bring Webpages
to life.
 Using JavaScript, you can control and
interact with all of the elements in a
webpage.

9
XP
Writing a JavaScript Program

 The Web browser runs a JavaScript program when


the Web page is first loaded, or in response to an
event.
 JavaScript programs can either be placed directly
into the HTML file or they can be saved in external
files.
◦ placing a program in an external file allows you
to hide the program code from the user
◦ source code placed directly in the HTML file can
be viewed by anyone
10
XP
Writing a JavaScript Program

 A JavaScript program can be placed anywhere within


the HTML file.
 Many programmers favor placing their programs
between <head> tags in order to separate the
programming code from the Web page content and
layout.
 Some programmers prefer placing programs within the
body of the Web page at the location where the
program output is generated and displayed.
 Sometimes it’s better to place JavaScript code at the
end of the page, so the code will be executed when the
whole page is loaded. 11
XP
Using the <script> Tag

 To embed a client-side script in a Web page, use the


element:
<script type=“text/javascript” >
script commands and comments
</script>
 To access an external script, use:
<script src=“url” type=“text/javascript”>
script commands and comments
</script>

12
XP
Comments
 The syntax for a single-line comment is:
// comment text
 The syntax of a multi-line comment is:
/*
comment text covering several lines
*/

13
XP
Hiding Script from Older Browsers
 You can hide the script from these browsers using
comment tags:
<script type=“text/javascript”>
<!-- Hide from non-JavaScript browsers
JavaScript commands
// Stop hiding from older browsers -->
</script>
 When a Web browser that doesn’t support scripts
encounters this code, it ignores the <script> tag.

14
XP
Writing Output to a Web Page
 JavaScript provides two methods to write text to a Web
page:
◦ document.write(“text”);
◦ document.writeln(“text”);
 The document.writeln() method differs from
document.write() in that it attaches a carriage return to
the end of each text string sent to the Web page.

document.write("<h3>News Flash!</h3><br />");

15
XP
JavaScript Syntax Issues
 JavaScript commands and names are case-sensitive.
 JavaScript command lines end with a semicolon to
separate it from the next command line in the
program.
◦ in some situations, the semicolon is optional
◦ semicolons are useful to make your code
easier to follow and interpret

16
XP
Working with Variables & Data

 A variable is a named element in a program that stores


information. The following restrictions apply to variable
names:
◦ the first character must be either a letter or an underscore
character ( _ )
◦ the remaining characters can be letters, numbers, or
underscore characters
◦ variable names cannot contain spaces
 Variable names are case-sensitive.
 document.write(Year);

17
XP
Types of Variables

JavaScript supports four different types of variables:


◦ numeric variables can be a number, such as 13, 22.5, or -
3.14159
◦ string variables is any group of characters, such as “Hello”
or “Happy Holidays!”
◦ Boolean variables are variables that accept one of two
values, either true or false
◦ null variables is a variable that has no value at all

18
XP
Declaring a Variable

 Before you can use a variable in your program, you need


to declare a variable using the var command or by
assigning the variable a value.
 Any of the following commands is a legitimate way of
creating a variable named “Month”:
var Month;
var Month = “December”;
Month = “December”;

19
Working with Expressions XP
and Operators
 Expressions are JavaScript commands that assign
values to variables.
 Expressions are created using variables, values, and
operators.
 The + operator performs the action of adding or
combining two elements. For example,
◦ var ThisMonth = 8+1;
◦ Var monthName = “Septem” + “ber”;

20
XP
Operators

 Binary operators work on two elements in an expression.


 Unary operators work on only one variable.
◦ unary operators include: the increment (++), decrement (-
-), and negation (-) operators.
 An increment operator is used to increase the value of the x
variable by one.
x = 100;
y = x++;

22
XP
Operators
 The decrement operator reduces the value of a
variable by 1.
x = 100;
y = x--;
 The negation operator changes the sign of a
variable:
x = -100;
y = -x;

23
XP
Assignment Operators

 Expressions assign values using assignment operators. “=”


is the most common one.
 Additional includes the += operator
 The following create the same results:
x = x + y;
x += y
 Either of the following increase the value of the x variable
by 2:
x = x + 2;
x += 2

24
Assignment Operators
XP
The Math Object & Math Methods

 Another way of performing a calculation is to use the


JavaScript built-in Math methods.
 These methods are applied to an object called the Math
object.
 The syntax for applying a Math method is:
value = Math.method(variable);
 For example,
AbsValue = Math.abs(NumVar);

26
XP
Creating JavaScript Functions

function function_name(parameters) {
JavaScript commands
}

◦ parameters are the values sent to the function (note: not


all functions require parameters)
◦ { and } are used to mark the beginning and end of the
commands in the function.

28
XP
Creating JavaScript Functions

 Function names are case-sensitive.


 The function name must begin with a letter or underscore (
_ ) and cannot contain any spaces.
 There is no limit to the number of function parameters that a
function may contain.
 The parameters must be placed within parentheses,
following the function name, and the parameters must be
separated by commas.

29
Performing an Action with a XP
Function
The following function displays a message:
function ShowMessage(name) {
document.write(“Hello ” + name + “<br>”);
}
◦ there is one line in the function’s command block, which
displays the current date along with a text string

30
Performing an Action with a XP
Function
To call the ShowDate function, enter:
var name = “Ahmed”;
ShowMessage(name);
◦ the first command creates a variable named “name” and
assigns it the text string, “Ahmed”
◦ the second command runs the ShowMessage function,
using the value of the name variable as a parameter
◦ result is “Hello Ahmed”

31
XP
Returning a Value from a Function

To use a function to calculate a value use the return command


along with a variable or value.
function Area(Width, Length) {
var Size = Width*Length;
return Size;
}
◦ the Area function calculates the area of a rectangular
region and places the value in a variable named “Size”
◦ the value of the Size variable is returned by the function

32
Placing a Function XP
in an HTML File
 The function definition must be placed before the
command that calls the function.
 One convention is to place all of the function definitions
in the <head> section.
 A function is executed only when called by another
JavaScript command.
 It’s common practice for JavaScript programmers to
create libraries of functions located in external files.

33
Working with Conditional XP
Statements
if (condition) {
JavaScript Commands
}
◦ condition is an expression that is either true or false
◦ if the condition is true, the JavaScript Commands in the
command block are executed
◦ if the condition is not true, then no action is taken

34
Comparison, Logical, and XP
Conditional Operators
To create a condition, you need one of three types of operators:
◦ a comparison operator compares the value of one
element with that of another, which creates a Boolean
expression that is either true or false
◦ a logical operator connects two or more Boolean
expressions
◦ a conditional operator tests whether a specific condition
is true and returns one value if the condition is true and a
different value if the condition is false

35
An Example of XP
Boolean Expressions
 x < 100;
◦ if x is less than 100, this expression returns the value
true; however, if x is 100 or greater, the expression is
false
 y == 20;
◦ the y variable must have an exact value of 20 for the
expression to be true
◦ comparison operator uses a double equal sign (==)

36
XP
Comparison Operators

37
XP
A Logical Operator

 The logical operator && returns a value of true only if all


of the Boolean expressions are true.

38
XP
A Conditional Operator
tests whether a specific condition is true and returns one
value if the condition is true and a different value if the
condition is false.
◦ Message = (mail == “Yes”) ? “You have mail”: “No
mail”;
◦ tests whether the mail variable is equal to the value
“Yes”
 if it is, the Message variable has the value “You
have mail”;
 otherwise, the Message variable has the value
“No mail”.

39
XP
Using an If...Else Statement

if (condition) {
JavaScript Commands if true
} else
JavaScript Commands if false
}
◦ condition is an expression that is either true or false, and
one set of commands is run if the expression is true, and
another is run if the expression is false

40
XP
Using Arrays

 An array is an ordered collection of values referenced by a


single variable name.
 The syntax for creating an array variable is:
var variable = new Array(size);
◦ variable is the name of the array variable
◦ size is the number of elements in the array (optional)
 To populate the array with values, use:
variable[i]=value;
where i is the ith item of the array. The 1st item has an index
value of 0.

41
XP
Using Arrays

To create and populate the array in a single statement, use:


var variable = new Array(values);
◦ values are the array elements enclosed in quotes and
separated by commas
◦ var MonthTxt=new Array(“”, “January”, “February”,
“March”, “April”, “May”, “June”, “July”, “August”,
“September”, “October”, “November”, “December”);
 January will have an index value of “1”.

42
<script type="text/javascript">
var Today=new Date();
var ThisDay=Today.getDate();
var ThisMonth=Today.getMonth()+1;
var ThisYear=Today.getFullYear();
var DaysLeft=XmasDays(Today);
var MonthTxt = new Array("", "January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October","November", "December");
document.write("Today is "+MonthTxt[ThisMonth]+" " +
ThisDay+", "+ThisYear+"<br />");
if (DaysLeft > 0) {
document.write("Only "+DaysLeft+" days until Christmas");
} else {
document.write("Happy Holidays from North Pole
Novelties");
}
</script>
Creating the MonthText Function in library2.js
function MonthTxt(MonthNumber) {
var Month=new Array();
Month[0]="";
Month[1]="January";
Month[2]="February";
Month[3]="March";
Month[4]="April";
Month[5]="May";
Month[6]="June";
Month[7]="July";
Month[8]="August";
Month[9]="September";
Month[10]="October";
Month[11]="November";
Month[12]="December";
return Month[MonthNumber];
}
Calling the MonthTxt Function
use the ThisMonth variable
to call the MonthTxt function
and then stores the result in
a new variable named “MonthName”

<head>
<script src="library2.js"
type="text/javascript"></script>
</head>

var MonthName=MonthTxt(ThisMonth);
XP
Working with Program Loops

 A program loop is a set of instructions that is


executed repeatedly.
 There are two types of loops:
◦ loops that repeat a set number of times before
quitting
◦ loops that repeat as long as a certain condition is
met

46
XP
The For Loop

 The For loop allows you to create a group of commands to


be executed a set number of times through the use of a
counter that tracks the number of times the command block
has been run.
 Set an initial value for the counter, and each time the
command block is executed, the counter changes in value.
 When the counter reaches a value above or below a certain
stopping value, the loop ends.

47
XP
The For Loop Continued

for (start; condition; update) {


JavaScript Commands
}
◦ start is the starting value of the counter
◦ condition is a Boolean expression that must be true for the
loop to continue
◦ update specifies how the counter changes in value each
time the command block is executed

48
Specifying Counter Values in a For Loop
XP
The While Loop

 The While loop runs a command group as long as a specific


condition is met, but it does not employ any counters.
 The general syntax of the While loop is:
while (condition) {
JavaScript Commands
}
◦ condition is a Boolean expression that can be either true
or false

52
DOM and JavaScript
Prepared by Mohammed Jabari

Mohammed Jabari 1
DOM
 DOM stands for Document Object Model.
 DOM allows you to programmatically
access any HTML Element.
 When the page is loaded, the Browser
creates Document Object Model of all
elements in the HTML Document
 DOM is platform and language
independent

Mohammed Jabari 2
DOM and JavaScript
 Using JavaScript you can access any
HTML element in the document and:
◦ change all the HTML elements in the page
◦ change all the HTML attributes in the page
◦ change all the CSS styles in the page
◦ remove existing HTML elements and
attributes
◦ add new HTML elements and attributes
◦ react to all existing HTML events in the page
◦ create new HTML events in the page

Mohammed Jabari 3
DOM and JavaScript
 To access a specific HTML element in the
document, that element must have a
unique id
 That is done using the id attribute:
 Example:
<div id=‘container’ > …. </div>
<h1 id=‘title’ > …. </div>

Mohammed Jabari 4
DOM and JavaScript
Accessing HTML elements using JavaScript:

1. Using element Id:


document.getElementById(‘id’)

2. Using the tag name:


document.getElementByTagName(‘tagname’)

3. Using class Name:


document.getElementByClassName(‘classname’)

Mohammed Jabari 5
DOM and JavaScript
 Changing HTML elements
document.getElementById(‘id’).innerHTML = “value”;
document.getElementById(‘id’).attribute= “value”;
document.getElementById(‘id’).style.attribute=
“value”;

 Adding or removing HTML elements:


◦ document.createElement()
◦ document.removeChild()

Mohammed Jabari 6
DOM and JavaScript
 Adding event handlers:
document.getElementById(‘id’).onclick
= function(){ …. }

Mohammed Jabari 7
JQuery
 Is a JavaScript library that greatly
simplifies the writing JavaScript
programs.
 JQuery is light weight, write less, do more
Javascript library
 The purpose of JQuery is make it much
easier to write JavaScript on websites.

Mohammed Jabari 8
JQuery
To use JQuery with your website you might:
1. Download the library from jquery.com and
include it in the head section of the website
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
2. Or, Include jquery from google
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.1
0.2/jquery.min.js">
</script>
</head>

Mohammed Jabari 9
JQuery
 For complete reference on JQuery refer
to:

http://www.w3schools.com/jquery/default.a
sp

You are required to finish the first section


which ends at JQuery events

Mohammed Jabari 10
References
 W3schools.com

Mohammed Jabari 11
1

JQUERY
Adapted from w3schools
Prepared by: Mohammed Jabari
2

What it is?
• A JavaScript library
• Greatly simplifies writing JavaScript programs
3

How to use JQuery


here are several ways to start using jQuery on your web
site. You can:
1. Download the jQuery library from jQuery.com
2. Include jQuery from a CDN, like Google

• Which way is better?


• What is a CDN?
4

How to use JQuery

1. The jQuery library is a single JavaScript file, and you


reference it with the HTML <script> tag (notice that the
<script> tag should be inside the <head> section):

<head>
<script src="jquery-3.2.1.min.js"></script>
</head>
5

How to use JQuery


2. If you don't want to download and host jQuery yourself,
you can include it from a CDN (Content Delivery Network).
To use jQuery from Google or Microsoft, use one of the
following:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.
11.3/jquery.min.js"></script>
</head>
6

jQuery Syntax

The jQuery syntax is tailor made


for selecting HTML elements and performing
some action on the element(s).
Basic syntax is:
$(selector).action( )

• A $ sign to define/access jQuery


• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)
7

jQuery Syntax

• Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
8

The Document Ready Event


$(document).ready(function(){

// jQuery methods go here...

});

• This is to prevent any jQuery code from running before


the document is finished loading (is ready).
9

jQuery Selectors

• The element Selector:


The jQuery element selector selects elements based on the
element name.
Example:

$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
10

jQuery Selectors

• The #id Selector:


The jQuery #id selector uses the id attribute of an HTML
tag to find the specific element.
Example: When a user clicks on a button, the element with
id="test" will be hidden:

$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
11

jQuery Selectors

• The .class Selector:


The jQuery class selector finds elements with a specific
class.
Example: When a user clicks on a button, the elements
with class="test" will be hidden:

$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
12

jQuery Event Methods

• An event represents the precise moment when something


happens.
Examples:
• moving a mouse over an element
• selecting a radio button
• clicking on an element

Mouse Events Keyboard Events Form Events Document/Window Events


click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload
13

jQuery Event Methods

• Example: To assign a click event to all paragraphs on a


page, you can do this:

$("p").click(function(){
// action goes here!!
});
14

jQuery Event Methods

• Example: dblclick()

$("p").dblclick(function(){
$(this).hide();
});
15

jQuery Event Methods

• Example: mouseenter()

$("#p1").mouseenter(function(){
alert("You entered p1!");
});
16

jQuery Event Methods

• Example: mouseleave()

$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
17

jQuery Event Methods

• Example: mousedown()

$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
18

jQuery Event Methods

• Example: hover()
The first function is executed when the mouse enters the
HTML element, and the second function is executed when
the mouse leaves the HTML element:

$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
19

jQuery Effects
• jQuery hide() and show()

$("#hide").click(function(){
$("p").hide();
});

$("#show").click(function(){
$("p").show();
});
20

jQuery Effects
• Hide and show with parameters

$("button").click(function(){
$("p").hide(1000);
});
21

jQuery Effects
• jQuery toggle()
With jQuery, you can toggle between the hide() and show()
methods with the toggle() method.

$("button").click(function(){
$("p").toggle();
});
22

jQuery and CSS


To change single CSS property value:

css("propertyname","value");

Example:

$(”#button1").click(function(){
$(“h1”).css("background-color", ”#ccc");
});
23

jQuery and CSS


• To change group of CSS values:

css({"propertyname":"value","propertyname":"value",...});

Example:

$("p").css({"background-color": "yellow", "font-size": "200%"});


24

• For more information refer to:


• www.w3schools.com
Bootstrap
What is Bootstrap?
• Bootstrap is a popular front-end framework that provides pre-
designed templates and tools to help developers create responsive
and mobile-first websites quickly and easily.
• Bootstrap is based on HTML, CSS, and JavaScript and is open-source,
meaning that it's free to use and customize.
• Current Bootstrap version is v5.3
• Official Website: https://getbootstrap.com/
How to use Bootstrap?
Option 1
1.Download Bootstrap: You can download the Bootstrap CSS and
JavaScript files from the official website.
2.Include Bootstrap files: After downloading Bootstrap, you need to
include the CSS and JavaScript files in your project. You can do this by
adding the following code to your HTML file:
How to use Bootstrap?
Option 2
• You can also use the Bootstrap CDN (Content Delivery Network) to
include the files. This can be useful for faster loading times and better
performance. Why?
Start using Bootstrap
• Once you have included the Bootstrap files in your project, you can
start using the pre-designed templates and tools that Bootstrap
provides.
• You can use Bootstrap classes in your HTML elements to style them.
For example, to create a button, you can use the following code:
Customize Bootstrap
• Bootstrap provides a lot of customization options that you can use to
make your website look unique.
• You can customize the color scheme, fonts, and other elements of
Bootstrap by using the Sass files that come with Bootstrap.
• You can also override Bootstrap's default styles by creating your own
CSS file and including it after the Bootstrap CSS file.
What is Sass?
• Sass (short for "Syntactically Awesome Style Sheets") is a
preprocessor scripting language that extends the capabilities of CSS.
• It allows you to use variables, functions, and other programming
concepts in your stylesheet, making it easier and more efficient to
write and maintain CSS code.
• Sass files are files that contain Sass code, which is then compiled into
regular CSS code that can be used in your web pages. Sass files have
the file extension ".scss" (for the newer "Sassy CSS" syntax) or ".sass"
(for the older, more concise syntax).
Bootstrap Grid System
• The Bootstrap grid system is a powerful, responsive layout system
that allows you to create flexible and dynamic layouts for your web
pages.
• The grid system is based on a 12-column layout, which you can
customize and use to create layouts for different screen sizes and
devices.
Bootstrap Grid System
• The Bootstrap grid system is based on the use of rows and columns.

• In this example, the row class creates a new row, and the col-md-6 class is
applied to each column to specify that it should take up 6 of the 12
available columns on screens that are medium-sized (or larger).
• The -md- part of the class name is a breakpoint, which indicates that the
column should apply to screens with a width of at least 768 pixels.
Bootstrap Grid break-points
• Bootstrap provides several breakpoint classes that allow you to create
responsive designs that adapt to different screen sizes. These classes
are used to specify different column widths for different screen sizes
Bootstrap Grid break-points
• To use these classes, you would typically combine them with the col
class to specify the width of a column.
• For example, if you want a column to take up 6 out of 12 columns on
small screens and 4 out of 12 columns on medium-sized screens, you
could use the following markup:
Bootstrap Grid break-points
• If you use the col class without any breakpoint, the column will take
up the full width of the row on all screen sizes.
• This is equivalent to using the col-12 class, which specifies that the
column should take up 12 out of the 12 available columns. For
example:
Bootstrap Grid break-points – equal-width
columns
• If you want to create a layout with multiple equal-width columns, you
can still use the col class,
• For example, if you want to create a layout with three equal-width
columns, you can use the following markup:
Bootstrap Container class
• It's typically used as a parent element for other Bootstrap components,
such as the grid system.
• There are two variations of the container class in Bootstrap:

1.‘container’: This class creates a container with a fixed width based on the
screen size. The width of the container changes at each breakpoint, so that
the content remains centered and readable on different devices.
2.‘container-fluid’: This class creates a full-width container that spans the
entire width of the viewport. It doesn't have any fixed width, and adjusts to
the size of the screen, regardless of the device or viewport width.
Bootstrap Container class
• Example
Bootstrap Container class
Bootstrap and Flexbox
• Bootstrap 4 and later versions use the Flexbox layout model for its grid
system.
• Flexbox is a powerful layout model that allows you to create flexible and
responsive layouts, and it is supported by most modern browsers.
• The Bootstrap grid system is based on a set of classes that allow you to
create rows and columns, and to specify the width and alignment of each
column.
• By default, the columns are set to display: flex, which allows them to
expand and shrink to fill the available space.

Introduction to
Python: history and statistics
• Python is a high-level programming
language created by Guido van Rossum in
the late 1980s.
• Python is an interpreted language, which
means that it is executed line by line.
• Python is a versatile language used for a
variety of tasks such as web development,
data analysis, artificial intelligence, and
more.
• Python is very popular language.

2
Installing Python
• Python can be installed on Windows, Mac, and Linux operating systems.
• Download the latest version of Python from the official website:
https://www.python.org/downloads/
• Latest version is python 3.11
• Install Python by following the prompts in the installation wizard.
• You will need an IDE
• What is an IDE?
• Use Pycharm community version, you can download it from:
https://www.jetbrains.com/pycharm/download

3
Python is easy to lean
• Python is one of the easiest programming languages to
learn
• You achieve more in Python per-statement than most
languages.
• The print() function is used to output text to the screen.
• Example: print("Hello, World!")
• Output: Hello, World!
• Python has its own style to make sure you code is clean and
readable
4
Programming language Syntax
• Just like any spoken language, programming languages have their own
syntax.
• What is a Syntax?
• A Set of words, symboles, and apperviations
• A Set of rules that govern the use of the the above to create valid sentances.
(Grammar)
• For a Python program to run correctly, it must have a valid syntax

5
Execute a Python code
• Python code can be executed directly in the command line
• If you have installed python, you can directly write and execute code
on the command line
• This way is useful to try and test small code portions

6
Execute a Python code
• You can execute a python file using the command line
• This way is more suitable for running store programs

7
Python code indentation
• Code indentation is used by Python to visually and syntactically
structure the program.
• A code indentation is the spaces at the beginning of the line code, it
can take one of the two styles:
• Tab
• 4 spaces

• You should not mix between the two indentation styles.

8
Python Data Types
• Data Types are basic
building blocks of a
program,
• They are used to
represent and store data
• Python has the following
built-in types:

9
Python Data Types

10
Python Operators: Arithmetic

11
Python Operators: Assignment

12
Python Operators: Comparison

13
Python Operators: Logical

14
Python Operators: Precendence Rules

15
Comments in Python
• In Python, comments are annotations within the code that are
ignored by the Python interpreter during execution.
• They are used to add explanatory notes, documentations, or
temporary remarks to the code, which can help other developers
understand the code or remind the author of its purpose.
• Python supports two types of comments:
• Single-line comments
• Multi-line comments

16
Comments in Python
Single-line comments:
• Single-line comments start with the # symbol and continue until the
end of the line.
• Anything after the # symbol on the same line is considered a
comment and is ignored by the interpreter.
# This is a single-line comment
print("Hello, World!") # This is another single-line comment

17
Comments in Python
Multi-line comments:
• you can use multi-line strings (also known as docstrings) multi-line
comments.
• It uses the triple quotation mark
"""
This is a multi-line comment.
It spans multiple lines.
"""
print("Hello, World!")

18
Identifiers in Python
• In programming, an identifier is a name given to a variable, function,
class, module, or any other user-defined item.
• Identifiers are used to uniquely identify these elements within the
program.
• They serve as labels that represent specific pieces of data or
functionality.

19
Identifiers Naming Rules
1. An identifier name must not start with a digit
2. An identifier name must not contain special symbol like (+, -, *)
3. An identifier name must not use reserved words like (if, else, fun, ..)
4. An identifier name must not contain a space
5. An identifier is case-sensitive, “Average” is not the same as
“average”

20
Identifiers Naming Rules
• Valid identifiers examples:
variable_name = 42
my_variable = "Hello"
_class = "MyClass"
CONSTANT_VALUE = 3.14
_this_is_a_valid_identifier = True
snake_case_variable = 100

• Invalid identifiers examples:


2nd_variable = 42 # Starts with a digit
if = 10 # Reserved word used as an identifier
my-variable = 5 # Contains a hyphen instead of an underscore
class = "MyClass" # Reserved word used as an identifier
variable name = 42 # Contains space
21
Python
Lists, Tuples, Sets, and Dictionaries
Lists
• list is an ordered collection of elements.
• Each element in a list can be of any data type, such as strings,
integers, or other objects.
• Lists are mutable, which means that you can add, delete, or modify
the elements in the list.
Lists
• Creating List:
You can create a list by enclosing a comma-separated sequence of
elements in square brackets []. For example:
Lists
• Accessing Elements in a List:
You can access elements in a list by their index, which starts from 0. For
example:
Lists
• Slicing a List:
You can also access a range of elements in a list by using slicing. Slicing
is done by specifying the start and end indices separated by a colon.

For example:
Lists
• More on Slicing
Lists
• More on Slicing
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get elements from index 2 to index 5 (exclusive)


sliced_list = my_list[2:5]
print(sliced_list) # Output: [2, 3, 4]

# Get elements from index 0 to index 7 (exclusive), with a step size of 2


sliced_list = my_list[0:7:2]
print(sliced_list) # Output: [0, 2, 4, 6]

# Get elements from index 3 to the end of the list


sliced_list = my_list[3:]
print(sliced_list) # Output: [3, 4, 5, 6, 7, 8, 9]
Lists
• More on Slicing
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get the last 3 elements of the list


sliced_list = my_list[-3:]
print(sliced_list) # Output: [7, 8, 9]

# Reverse the list


reversed_list = my_list[::-1]
print(reversed_list) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Lists
• Modifying Elements in a List:
You can modify an element in a list by assigning a new value to it using
its index. For example:
Lists
• Adding Elements to a List:
You can add elements to a list using the append() method. For
example:
Lists
• Adding two lists
Using the + operator: You can concatenate two lists using the +
operator.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
Lists
• Adding two lists
Using the extend() method:
You can also use the extend() method to add elements from one list to
another.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
Lists
• Removing Elements from a List:
You can remove elements from a list using the remove() method. For
example:
Lists
• Removing Elements from a List:
Using pop() method: If you want to remove and return the element at a
specific index, you can use the pop() method.
my_list = [1, 2, 3, 4, 5]
removed_element = my_list.pop(2) # Removes and returns the element at index 2 (3)
print(my_list) # Output: [1, 2, 4, 5]
print(removed_element) # Output: 3
Lists
• Removing Elements from a List:
Using del statement: If you know the index of the element you want to
remove, you can use the del statement.
my_list = [1, 2, 3, 4, 5]
del my_list[2] # Removes the element at index 2 (3)
print(my_list) # Output: [1, 2, 4, 5]
Tuples
• A tuple is a collection of elements enclosed in parentheses and
separated by commas.
• Tuples are similar to lists, but they are immutable, which means you
cannot modify their contents after they have been created.

• It can also be created without parentheses:


Tuples
• Tuples support indexing and slicing, just like lists.
Here's an example of indexing a tuple:
Tuples
• Tuples can be nested:
Set
• A set is an unordered collection of unique elements.
• Sets are defined by enclosing a comma-separated list of elements
within curly braces {}. Here's an example:

• You can also create a set using the set() function and passing a list,
tuple or any other iterable object as an argument:
Set
• Sets do not allow duplicate elements, so any duplicate elements in
the input are automatically removed when creating a set. Here's an
example:
Set
• Adding elements to Set:

• Removing element from set:


Dictionary
• A dictionary is an unordered collection of key-value pairs.
• Dictionaries are defined using curly braces {} and key-value pairs are
separated by a colon :. Here's an example of a dictionary:
Dictionary
• You can also add, remove, and modify key-value pairs in a dictionary.
Here's an example of adding a new key-value pair:
my_dict = {"apple": 2.99, "banana": 1.99, "orange": 0.99}
my_dict["kiwi"] = 3.99
print(my_dict) # Output: {"apple": 2.99, "banana": 1.99, "orange": 0.99, "kiwi": 3.99}

• Removing a key-value pair:


Python
Control Flow
Program Flow of Control
• Flow of control in a program refers to the order in which instructions
are executed. There are three main forms of flow of control in
programming, sequential, conditional, and repetition (looping).

• Each of these forms of flow of control has its own syntax and
structure in programming languages. By using a combination of these
forms, programmers can create complex programs that can perform a
wide range of tasks.
Program Flow of Control
1 Sequential flow:
• In sequential flow, instructions are
executed in the order in which they
appear in the program.
• This is the most basic form of flow of
control and is used in most programs.
Program Flow of Control
2. Conditional flow:
• In conditional flow, the program executes
different instructions depending on
whether a certain condition is true or
false.
• For example, if the condition "x > 5" is
true, the program might execute one set
of instructions, and if it is false, it might
execute a different set of instructions.
Program Flow of Control
3. Looping flow:
• In looping flow, the program
executes the same set of
instructions multiple times.
• These are used when the same set
of instructions needs to be executed
multiple times.
Conditional Statements
• Python's if statement allows us to conditionally execute a block of
code based on a certain condition. It has the following syntax:

• Here's an example of using the if statement to check if a number is


positive: (notice the indentation)

• Output:
The number is positive
Conditional Statements
• The if-else statement in Python allows us to execute one block of
code if a condition is True, and another block of code if it's False. It
has the following syntax:
Conditional Statements
• Here's an example of using the if-else statement to check if a number is
positive or negative: (notice the indentation)

• Output: The number is negative


Conditional Statements
• We can also chain multiple if-else statements together using elif,
which is short for "else if". It allows us to check multiple conditions
and execute different code blocks based on those conditions. Here's
the syntax:
Conditional Statements
• Here's an example of using if-elif-else statement to check if a number is positive,
negative or zero:

• Output: The number is zero


• HW1 (Currency Covertor):
• Requirements:
1. Asks user to enter amount in USD
2. Check if the entered amount is valid, i.e > 0
3. Convert the entered amount to LIS
4. Output the result
• Due date: 2023-03-23 by midnight
• Submit you code file to eclass
Python
Control Flow (Loops)
Program Flow of Control
Looping flow:
• In looping flow, the program
executes the same set of
instructions multiple times.
• These are used when the same set
of instructions needs to be executed
multiple times.
Loops in Python
• Loops are an important concept in programming, including in the
Python language.
• Loops enable repetitive execution of a block of code. Python supports
two types of loops: for loops and while loops.
While loops
• While loops are used to repeatedly execute a block of code as long as a
certain condition is true.
• The syntax for a while loop is
while condition:
statements
where condition is an expression that evaluates to either True or False.
• A while loop can also have an else clause, which is executed when the loop
has completed all iterations.
• It's important to ensure that the condition in a while loop eventually
becomes False, otherwise, the loop will execute indefinitely (also known as
an infinite loop).
While loops
Example 1:
• Notice how the value for i, the counter, is initialized to 0
• Notice the indentation
• Notice how the value of i is changing inside the while block
While loops
Example 2:

• In this example the while loops is


followed by an else
• The else block will be executed
when all the loop iterations are
completed
While loops
Example 3:
for all numbers between 0 and 100, print those that are divisable by 9
For loops
• For loops are used to iterate over a sequence (like a list, tuple,
dictionary, or string).
• The syntax for a for loop is:
for element in sequence:
where element is a variable that takes on each value in sequence.
For loops
Example 1: (loop over a list)

The output will be:


For loops
Example 2: (loop over a tuple)

The output will be:


For loops
Example 3: (loop over a dictionary)

In this example we are using items() method on fruits dictionary to


return all dictionary items as tuples of key-value pairs
The output will be:
The range function
• The range() function is commonly used with for loops to specify the
number of iterations.
• Example:
The range function
The range() function in Python is used to generate a sequence of
numbers.
The range() function can take up to three arguments:
1.start (optional): The starting value of the sequence (inclusive). The
default value is 0 if this argument is not provided.
2.stop: The ending value of the sequence. This argument is required.
3.step (optional): The step value between each number in the
sequence. The default value is 1 if this argument is not provided.
The range function
Examples:
1. In this example, i will start with the value 2

2. In this example, i will take two steps each time.


Loop Control Statements
• Loop control statements are used to control the execution of loops.
• Loop control statements are break, continue, and pass
• The break statement is used to exit a loop prematurely
• The continue statement is used to skip over an iteration.
• The pass statement can be used as a placeholder when a statement is
required syntactically, but you don't want to execute any code.
Loop Control Statements (Example)
Using break:
In this example the loop will stop (break)
when the value of i equals 3
The output will be:
0
1
2
Loop Control Statements (Example)
Using continue:
In this example, the loop will skip any
statement/s after the continue and
proceed to the next iteration
The output will be:
0
1
2
4
Loop Control Statements (Example)
• Using pass:
pass is used as placeholder, i.e. just to
make the statement syntactically
correct.
The output of this code will be nothing
Nested Loops
• It's possible to have loops within loops, also known as nested loops.
• Nested loops can be useful for iterating over multi-dimensional data
structures like matrices or nested lists.
• It's important to be mindful of the number of iterations in nested
loops, as they can quickly become computationally expensive.
Nested Loops (Example)
• Notice how we have two while
loops
• Notice the two indentation levels
Nested Loops (Example)
• Using two for loops
• Notice the two indentation levels
Python
Functions

1
What is a function?
• Functions are blocks of reusable code that perform a specific task.
• Functions are defined using the def keyword, followed by the function
name, parentheses, and a colon.
• Function parameters can be defined within the parentheses,
separated by commas.
• The body of the function is indented and contains the code to be
executed.
• Functions are great way to logically divide your code so it can be
easily reused, tested, and understood

2
Declaring a function
Example 1:

Notice the following:


• Function delaration starts with the keyword def
• The function name is greet
• The function takes name as an argument (parameter)
• The function body (block) is indented

3
Calling a function
• Functions are called or invoked using their name followed by
parentheses.
• Arguments can be passed to the function within the parentheses.
• The function is executed and the result, if any, is returned.
• To call the function we declared in the previous example:

4
Return statment
• Functions can return a value using the return statement.
• The returned value can be assigned to a variable or used directly in an
expression.
• Think of a function that takes two numbers and returns the max, or a
function that takes two numbers and returns the sum

5
Return statment
Example:

• The function name is add, It takes two arguments, a and b


• Notice the use of keyword return
• This function when called will return a value
• In the above example, the returned value is assigned to result
• The text within the triple quotes is just a note for documentation

6
Return statement
Example 2:

Calling the function:

The output:

7
Default arguments
• Functions can have default values for their parameters.
• If a value is not provided for a parameter during function call, the
default value is used.
• A default value is declared by appending the parameter name with =
value

8
Default arguments
Example:

• Notice how the argument greeting is written


• If this function is called without passing a value for greeting, the default
value “Hello” will be used
9
Python
String built-in Functions

1
String Type
• In Python, a string is a sequence of characters and is defined as a
built-in data type.
• Strings are immutable, meaning that once a string is created, it
cannot be modified in place.
• Instead, any operation that appears to modify a string actually creates
a new string object.
• To define a string in Python, you can simply enclose a sequence of
characters in either single quotes ('...') or double quotes ("..."). Here's
an example:

2
String Built-in Functions
• Python has a wide variety of built-in functions that are used to
manipulate strings.
• Here are some of the most commonly used string functions in
Python:

3
String Built-in Functions
str.len() : Returns the length of a string.

str.upper() : Returns the uppercase version of a string.

str.lower() : Returns the lowercase version of a string.

4
String Built-in Functions
str.capitalize() : Capitalizes the first letter of a string.

str.title() : Capitalizes the first letter of each word in a string.

str.strip() : Removes any whitespace from the beginning and end of a


string.

5
String Built-in Functions
str.replace(old, new) : Replaces all occurrences of old in a string with
new.

str.find(substring) : Finds the first occurrence of substring in a string


and returns its index.

6
String Built-in Functions
str.startswith(prefix) : Returns True if the string starts with prefix,
otherwise False.

str.endswith(suffix) : Returns True if the string ends with suffix,


otherwise False.

7
String Built-in Functions
str.split(separator) : Splits the string into a list of substrings at each
occurrence of separator.

str.join(iterable) : Joins the elements of iterable (e.g. a list) into a single


string, separated by str.

8
String Built-in Functions
str.isalpha() : Returns True if all characters in the string are alphabetic,
otherwise False.

str.isdigit() : Returns True if all characters in the string are digits,


otherwise False.

9
String Built-in Functions
str.isalnum() : Returns True if all characters in the string are
alphanumeric, otherwise False.

10
HW: Password Strength Checker
Write a Python program that checks the strength of a given password. A strong password
should contain a mix of uppercase and lowercase letters, numbers, and special characters.
Your program should do the following:
1.Prompt the user to enter a password.
2.Check the length of the password using the len() function. A strong password should be
at least 8 characters long.
3.Check if the password contains at least one uppercase letter, one lowercase letter, one
number, and one special character using the str.isupper(), str.islower(), str.isdigit(), and
str.isalnum() functions.
4.Assign a strength score to the password based on the above criteria. For example, a
password that meets all the criteria can be assigned a score of 5, while a password that
only meets one criteria can be assigned a score of 1.
5.Print a message to the user indicating the strength of the password based on its score.

11
HW: Password Strength Checker
• Sample Output:

12
Python
Object Oriented
Object Oriented Programming
• Object-oriented programming (OOP) is a programming paradigm that
focuses on organizing code into reusable objects that contain both
data (attributes) and behavior (methods).
• As opposed to functions, a function only defines the behavior, while
the class contains in addition to that, attributes (data)
• Python fully supports OOP and provides the necessary mechanisms to
define classes, create objects, and interact with them.
Classes and Objects:
• A class is a blueprint or template for creating objects. It defines the
attributes and methods that the objects will have.
• To create an object of a class, you instantiate it using the class name
followed by parentheses.
Classes and Objects: Attributes
• Attributes are variables that hold data within an object.
• They define the state or characteristics of an object.
• You can define attributes in the class using the self keyword within
the class's methods.
In this example, the Person class has two
attributes: name and age. The __init__ method is
a special method called the constructor, which
initializes the attributes when a new object is
created. The self parameter refers to the object
being created.
Classes and Objects: Methods
• Methods are functions defined within a class.
• They define the behavior or actions that an object can perform.
Similar to attributes, methods have access to the object's attributes
through the self parameter.
In the above example, the Circle class has an
attribute radius and a method
calculate_area(). The method uses the
self.radius attribute to perform a computation
and return the area of the circle.
Back-end
Web Technologies
Prepared By
Mohammed Jabari
Client-Server Architecture
• Web Started very simple:
• A client (Browser) requests a file from a remote server
• The server, returns the requested file in the response.
Web Today
Modern Web Technologies
• Today, it’s all about using a Framework
• So, what is a Framework?
• The skeleton for your application to build on
• Enforces specific structure and best practices
• Set of predefined libraries, classes and methods
• Let you spend more time concentrating on the business specific problem,
rather than on the plumping code behind it

• Why using a Framework is better?


Why use a Web Framework?
• Framework enforces a standard
• Tested and reliable
• Save a lot of time
• Easy to maintain

But it takes some time to learn!

5
Framework vs. library, what is the difference?

• A Framework enforces specific structure the programmer must follow.


• A library is just a set of predefined functionalities, it does not enforce
any specific structure on the programmer
• Example of a library: jQuery
Modern Web Frameworks
Many Web Frameworks are out there:
– PHP Frameworks:
• Laravel
• CakePHP
• Zend
• And many others
– Python Frameworks:
• Django
• Flask
• Web2Py
– Node Framework:
• Express
• Next
• Java:
• Java Spring
• .Net C#:
• ASP.Net
Front-end vs Back-end
• The user sees and interacts with the front-end
• So, basically, front-end web technologies are the technologies that
run inside a browser:
• Angular
• Vue
• jQuery
• The back-end is the infrastructure that support the front-end
• Usually run on the server side, responsible for the data management
and the business logic of the application
Django
Adapted from w3schools

1
What is Django?
• Django is a Python framework that makes it easier to create web
sites using Python.
• Django takes care of the difficult stuff so that you can
concentrate on building your web applications.
• Django emphasizes reusability of components, also referred to as
DRY (Don't Repeat Yourself)
• comes with ready-to-use features like login system, database
connection and CRUD operations (Create Read Update Delete).

2
How does Django Work?
Django follows the MVT design pattern (Model View
Template).
• Model - The data you want to present, usually data
from a database.
• View - A request handler that returns the relevant
template and content - based on the request from the
user.
• Template - A text file (like an HTML file) containing the
layout of the web page, with logic on how to display the
data.
3
The Model (models.py)
• The model provides data from the database.
• In Django, the data is delivered as an Object Relational
Mapping (ORM), which is a technique designed to make it
easier to work with databases.
• The most common way to extract data from a database is
SQL. One problem with SQL is that you have to have a
pretty good understanding of the database structure to be
able to work with it.
• Django, with ORM, makes it easier to communicate with the
database, without having to write complex SQL statements.
• The models are usually located in a file called models.py.

4
The View (views.py)
• A view is a function or method that takes http requests
as arguments, imports the relevant model(s), and finds
out what data to send to the template, and returns the
final result.
• The views are usually located in a file called views.py.

5
The Template (.html)
• A template is a file where you describe how the result
should be represented.
• Templates are often .html files, with HTML code
describing the layout of a web page, but it can also be
in other file formats to present other results, but we will
concentrate on .html files.
• Django uses standard HTML to describe the layout, but
uses Django tags to add logic
• The templates of an application are located in a folder
named templates.
6
URLs (urls.py)
• Django also provides a way to navigate around the
different pages in a website.
• When a user requests a URL, Django decides
which view it will send it to.
• This is done in a file called urls.py.

7
How does Django work?

1. Django receives the URL, checks


the urls.py file, and calls the view that matches
the URL.
2. The view, located in views.py, checks for
relevant models.
3. The models are imported from
the models.py file.
4. The view then sends the data to a specified
template in the template folder.
5. The template contains HTML and Django tags,
and with the data it returns finished HTML
content back to the browser.

8
Installing Django
• Install Python: https://www.python.org/downloads/
• Install Django, follow the Django tutorial at:
https://www.w3schools.com/django/django_install_django.php
• Install PyCharm (Community) IDE:
https://www.jetbrains.com/pycharm/

9
Django Models
The Model
• Remember?
The Model
• In Django, the data is delivered as an Object Relational
Mapping (ORM), which is a technique designed to make
it easier to work with databases.
• Django, with ORM, makes it easier to communicate with
the database, without having to write complex SQL
statements.
The Model
• In Django, models are Python classes that represent database tables.
• They define the structure of the data and include methods for
querying, inserting, updating, and deleting records in the database.
• The Django Model API provides a powerful and intuitive way to
interact with your database without writing SQL queries directly.
Here's a detailed breakdown of the Django Model API:
Defining Models
• Models are typically defined in a models.py file within a Django app.
• Each model class is a subclass of django.db.models.Model.
• Model fields are defined as class attributes, representing the columns
in the corresponding database table.
• Django provides various field types such as CharField, IntegerField,
FloatField, BooleanField, DateField, DateTimeField, etc., to specify the
type of data each column can hold.
• Relationships between models are defined using ForeignKey,
OneToOneField, ManyToManyField, etc.
Defining Models
Creating Migrations
• After defining models, you need to create migrations to apply these
changes to the database schema.
• Django's makemigrations command generates migration files based
on changes to the models.
• Migration files are Python scripts that describe the changes to be
applied to the database schema, including creating tables, adding or
modifying columns, etc.
• The migrate command applies these migrations to the database.
Creating Migrations
• Creating the migrations
C:\djangoProjectFolder> python makemigrations app_name

• Applying the migrations


C:\djangoProjectFolder> python migrate app_name
Interacting with Models
• Querying data: Django provides a rich API for querying the database using the
objects attribute of model classes.
• Model.objects.all() : Retrieves all objects of a particular model.
• Model.objects.get() : Retrieves a single object based on specified criteria.
• Model.objects.filter() : Retrieves a queryset containing objects that match
specified criteria.
• Model.objects.create() : Creates a new object and saves it to the database.
• Modifying data: You can modify model instances and save them back to the
database using the save() method.
• Deleting data: Model instances can be deleted using the delete() method.
Interacting with Models
Querysets
• Querysets are lists of objects of a given model, with methods to filter,
order, and manipulate them.
• Querysets are lazy, meaning the actual database query is executed
only when the queryset is evaluated.
• You can chain multiple methods on a queryset to perform complex
queries.
• Common queryset methods include filter(), exclude(), order_by(),
annotate(), values(), count(), exists(), etc.
Querysets
Using Model Student with view and
template, and URl
The view:
The view here uses the Model ‘Student’ to retrieve all records and then passes
them to the template ‘student_list.html’ using the render function
Using Model Student with view and template
The Template:
The template uses the data passed to it from the view to display a list of students
Using Model Student with view and template
• URLs: Map the view to a URL in your Django app's urls.py.

• Now, when you visit the URL /students/ in your browser, Django will
render the student_list.html template, displaying a list of all students
along with their names, majors, and average grades.
prepared by Mohammed Jabari
STATE MANAGEMENT
1 Prepared by Mohammed Jabari
STATE MANAGEMENT
 What is State Management?
 Types of State Management

prepared by Mohammed Jabari


 Server-Side State Management
 Client-Side State Management

2
WHAT IS STATE MANAGEMENT?
 Session – is the connection that is established
between a user (the client computer) and a
Web server

prepared by Mohammed Jabari


 Sessions can span multiple Web pages and are
tracked through state management.

 State – is the ability of a Web application to


retain user information.

 State management – is the process by which


you maintain the same information
throughout multiple requests for the same or
different Web pages. 3
WHAT IS STATE MANAGEMENT?
Without State With State
Management Management
Login.php Login.php

prepared by Mohammed Jabari


Please enter your Please enter your
logon logon information:
information: First Name
John John
Last Name Last Name
Chen Chen

Submit Submit Web Server


Web Server
Greetings.php Greetings.php

Hello
Hello John Chen

I forget who
you are!!
4
IN BRIEF ..
▪ HTTP protocol is stateless, which means that it does
not automatically indicate whether the requests in a
sequence are all from the same client or not.

▪ Furthermore, Web pages are destroyed and then

prepared by Mohammed Jabari


recreated with each new request to the Web server;
therefore, page information does not exist beyond the
life cycle of a single page.

▪ State management that saves information on the


server between pages, which helps to maintain the
continuity of user information (state) throughout a
visit to a Web Site.

▪ If state is maintained between pages, the information


that is originally supplied by users can be reused;
consequently, users do not need to reenter the same
information multiple times each time a page is sent
back to the server. 5
TYPES OF STATE MANAGEMENT
Server-Side State Client-Side State
Management Management
Session state
Cookies
◼ Information is available only to a
user of a specific session ◼ Text file stores information to
maintain state

Database (or state server) Query strings


◼ In some cases, use database
◼ Information appended to the end of
support to maintain state on your
a URL
Web site
STATE MANAGEMENT IN DJANGO

 Django state management involves handling user


sessions, authentication, and maintaining user-
specific data across HTTP requests.
 Sessions are a way to store data for individual users
across requests.

Web Server
Client Computer
Session variables

SessionID
DJANGI: SESSIONS

• Django uses server-side sessions, where session data is


stored on the server, and a session identifier is sent to the
client as a cookie.
• By default, Django stores session data in a database table
(django_session) but can also use cache systems like Redis
or Memcached.
• You can access session data in views using the
request.session attribute, which behaves like a Python
dictionary.
• Session data can store user-specific information, such as
user IDs, preferences, or shopping cart items.
• Session data is typically serialized using JSON, but you can
customize the serialization format.
SETUP SESSIONS ON DJANOG

1. Enable Sessions: Ensure 'django.contrib.sessions' is


included in INSTALLED_APPS in your settings.py.
2. Middleware: Make sure SessionMiddleware is
enabled in your MIDDLEWARE setting.
SETUP SESSIONS ON DJANOG

3. Database Configuration: By default, Django uses


the database to store session data. Ensure your
database is configured correctly in settings.py.
SESSIONS: USAGE CODE

 Setting session data:

 Getting session data:


SESSIONS: USAGE CODE

 Deleting session data


COOKIES

 Cookies are small pieces of data sent by the server to


the user's browser and stored there. They are sent
back to the server with every request from the same
browser.
How Cookies work

1
Web 2 Does the Request has
The authentication
server cookie

 Authenticated

prepared by Mohammed Jabari


Not
Authenticated
Client requests page

Username
6 Someone 4 Authorized
Access Denied


Password
Logon Page
(Users enter
********** their credentials)
*
Not Submit
Authenticated 3
Authenticated

Authentication Authorized
Cookie 7 Requested
Secure Page
5

14
COOKIES: USAGE CODE
 Setting Cookie:

prepared by Mohammed Jabari


 Getting Cookie:

15
COOKIES: USAGE CODE
 Deleting Cookie:

prepared by Mohammed Jabari


16
AJAX
1 Prepared by: Mohammed Jabary
Adapted with minor changes from w3schools.com
WHAT IS AJAX?

 AJAX: Asynchronous Javascript And Xml


 It’s a technique to produce fast and dynamic
webpages
 AJAX allow web pages to be updated Asynchronously
by exchanging small data with the server behind the
scenes
 This means it’s possible to update parts of the web
page without the need to reload the whole page.
 Classic web pages (without AJAX), must reload the
whole page if the content should change
 Examples of websites using AJAX: Google Suggest, 2
Google map, Gmail, facebook, youtube
HOW DOES AJAX WORK?
AJAX is based on the Internet standards, and uses
combination of:
 XMLHttpRequest (to exchange data
asynchronously with the server)
 Javascript/DOM (to display/interact with data)

 CSS to style the data

 XML (often – not always – used as the format for


transfering data)
Note: AJAX is supposed to be Browser and
Platform independent (why?)
3
HOW DOES AJAX WORK?

4
EXAMPLE EXPLAINED
The following code represents a single <div> with a button, when the button
is clicked a function called “loadXMLDoc()” is called

<html>
<head>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>


<button type="button" onclick="loadXMLDoc()">Change Content<button>

</body>
</html>

5
CREATING JAVASCRIPT FUNCTION
The function to be called when the button is
clocked is defined in the script section in the
head of the html, add the following the head of
html document
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
// Ajax code goes here
}
</script>
</head>
6
CREATING XMLHTTPREQUEST OBJECT
 XMLHttpRequest is supported by most the
modern browsers (Chrome, Safari, Firefox)
 These browsers have build-in
XMLHttpRequest
 The XMLHttpRequest is used to exchanged
data asynchronously with the server
 Syntax for creating XMLHttpRequest:

// for most browsers


Variable = new XMLHttpRequest();

// for IE 5 and 6
7
Variable = new ActiveXObject(“Microsoft.XMLHTTP”);
 Creating XMLHttpRequest

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
8
SENDING A REQUEST TO THE SERVER
 Tosend a request to the server using
XMLHttpRequest we use its open and send
methods
 Syntax:
xmlhttp.open("GET",”getcomments.php",true);
xmlhttp.send();

Open(method, URL, Asyn);


Method: POST or GET
URL: the requested URL on server
Asyn: True/False. For asynchronous use true

Send(String);
Sends the request off to the server
9
String is used only with POST requests
WAITING FOR THE RESPONSE
 With AJAX, javascript does not have to wait for the server response, instead it
can:
 Execute other scripts while waiting for the response
 Deal with response when the response is ready
 Use the onreadystatechange event of the XMLHttpRequest to specify a function to
be executed when the response is ready

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
10
THE ONREADYSTATECHANGE EVENT
 After sending the request to the server, we want
to perform some actions based on the response
 The onreadystatechange event is triggered
every time the readystate changes
 The readystate property holds the status of the
XMLHttpRequest

11
THE RESPONSE
 The response object sent from the server can take
two forms:
 responseText: gets the response data as String
 responseXML: gets the response data as XML

12
T HE COMPLETE EXAMPLE
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
} 13
xmlhttp.open("GET",”getcomment.php",true);
xmlhttp.send();
COMPLETE EXAMPLE (CONT..)
<body>

<div id="myDiv"><h2>Let AJAX change this


text</h2></div>
<button type="button” id=“b1”
onclick="loadXMLDoc()">Change
Content</button>

</body>
</html>

14
AJAX USING JQUERY
 jQuery support AJAX calls
 The code to make AJAX calls is simple
 Syntax:

$(document).ready(function(){
$(”Selector").click(function(){
$.ajax({
url:”URL to page",
success:function(result){

$(”Selector").html(result);
}
});
});
15
});
AJAX USING JQUERY
 Rewriting the Previous Example using jQuery AJAX:

$(document).ready(function(){
$(”#b1").click(function(){
$.ajax({
url:”getcomment.php",
success:function(result){

$(”#myDiv").html(result);
}
});
}); 16
});
REFERNCES
 W3schools.com

17

You might also like