Final Web
Final Web
Mohammed Jabari
INTERNET AND WEB
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?
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)
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?
Mohammed Jabari
computers, open and transfer files, display text and
images.
Web browsers are specialized programs.
10
CLIENT/SERVER STRUCTURE OF THE WEB
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.
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)
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
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
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
Mohammed Jabari
HTTP, the Hypertext Transfer Protocol, is the
application-level protocol that is used to transfer
data on the Web.
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.
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.
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
1
IN THIS LECTURE
2
STATIC AND DYNAMIC WEB PAGES
Two kinds of web pages: static web pages and
dynamic web pages
3
STATIC WEB PAGES
A page whose content consists of some HTML code
and saved as an .htm or .html file
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 !!
Maintenance cost
10
DYNAMIC WEB PAGES
Constructed "on the fly" when a page is requested
11
ADVANTAGES OF DYNAMIC
WEB PAGES
In comparison to “Static web pages”, the
“Dynamic web pages” are:
slower
13
Web Technologies
Web Technologies can be classified into two
types:
14
Front-end (CLIENT-SIDE) WEB Technologies
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
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
request (URL)
<html>
<head><title>My First Web Page</title>
</head>
<body bgcolor="white">
<p>A Paragraph of Text.</p>
</body>
</html>
Nested Tags
<html>...</html>
<html>
<head><title>My First Web Page</title>
</head>
<body bgcolor="white">
<p>A Paragraph of Text.</p>
</body>
</html>
Basic Tags
• <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
• < → <
• > → >
• & → &
• → space
Anchor Tag (Links)
• <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>
Client Server
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
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
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 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;
}
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%; }
<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
<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>
</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
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
30
EXAMPLE
Consider the following CSS style:
width:250px;
padding:10px;
border:5px solid gray;
margin:10px;
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>
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 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:
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>.
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
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
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
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.
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
17
XP
Types of Variables
18
XP
Declaring a Variable
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
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
24
Assignment Operators
XP
The Math Object & Math Methods
26
XP
Creating JavaScript Functions
function function_name(parameters) {
JavaScript commands
}
28
XP
Creating JavaScript Functions
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
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
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
41
XP
Using Arrays
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
46
XP
The For Loop
47
XP
The For Loop Continued
48
Specifying Counter Values in a For Loop
XP
The While Loop
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:
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”;
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
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
<head>
<script src="jquery-3.2.1.min.js"></script>
</head>
5
jQuery Syntax
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
});
jQuery Selectors
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
10
jQuery Selectors
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
11
jQuery Selectors
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
12
$("p").click(function(){
// action goes here!!
});
14
• Example: dblclick()
$("p").dblclick(function(){
$(this).hide();
});
15
• Example: mouseenter()
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
16
• Example: mouseleave()
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
17
• Example: mousedown()
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
18
• 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
css("propertyname","value");
Example:
$(”#button1").click(function(){
$(“h1”).css("background-color", ”#ccc");
});
23
css({"propertyname":"value","propertyname":"value",...});
Example:
• 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
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
For example:
Lists
• More on Slicing
Lists
• More on Slicing
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
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.
• 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:
• 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:
• 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)
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:
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:
6
Return statement
Example 2:
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:
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.
4
String Built-in Functions
str.capitalize() : Capitalizes the first letter of a string.
5
String Built-in Functions
str.replace(old, new) : Replaces all occurrences of old in a string with
new.
6
String Built-in Functions
str.startswith(prefix) : Returns True if the string starts with prefix,
otherwise False.
7
String Built-in Functions
str.split(separator) : Splits the string into a list of substrings at each
occurrence of separator.
8
String Built-in Functions
str.isalpha() : Returns True if all characters in the string are alphabetic,
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
5
Framework vs. library, what is the difference?
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?
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
• 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
2
WHAT IS STATE MANAGEMENT?
Session – is the connection that is established
between a user (the client computer) and a
Web server
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.
Web Server
Client Computer
Session variables
SessionID
DJANGI: SESSIONS
1
Web 2 Does the Request has
The authentication
server cookie
Authenticated
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:
15
COOKIES: USAGE CODE
Deleting Cookie:
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>
</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 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();
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>
</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