You are on page 1of 191

AWP

What is HTML?
• HTML(Hyper Text Markup Language)
 is a language for describing web pages.
 not a programming language
 uses markup tags to describe web pages.
• Most Web documents are created using HTML.
 Documents are saved with extension .html or .htm.
• Markup?
 Markup Tags are strings in the language surrounded by a < and a > sign.
 Opening tag: <html> Ending tag: </html>
 Not case sensitive.
 Can have attributes which provide additional information about HTML
elements on your page. Example
o <body bgcolor="red">
o <table border="0">
3

HTML
• An HTML document appears as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>

 HTML Head Section: contain information about the document. The browser does
not display this information to the user. Following tags can be in the head section:
<base>, <link>, <meta>, <script>, <style>, and <title>.
 HTML Body Section: defines the document’s body. Contains all the contents of
the document (like text, images, colors, graphics, etc.).
4

Document (Body) Contents


• Body Text
 HTML truncates spaces in your text.
 Use <br> to insert new lines.
 Use <p> tag to create paragraphs.

• Comments in HTML Document


 Increase code readability; Ignored by the browser.
 Example of HTML comment: <!-- This is a Sample HTML Comment -->

• Physical Character Effects


 Bold Font: <b>…</b>
 Italic: <i>…</i>
 Underline: <u>…</u>
 Strikethrough: <strike> or <s>
 Fixed width font: <tt> - normal text in fixed-width font
 Subscript: <sub>
 Superscript: <sup>
5

Logical Character Effects


• Heading Styles:
 <hn>…………</hn>
o Value of n can range from 1 to 6
 <h1 align=“center”>This is level 1 heading</h1>

Using Heading styles

<html>
<head><title>This is the first html page</title>
<body>This is the first html page created
<h1 align=”left”>This is level 1 heading</h1>
<h2 align=”right”>This is level 2 heading</h2>
<h3 align=”center”>This is level 3 heading</h3>
</body>
</head>
</html>
6

Numbered List (Ordered List)


• Automatically generate numbers in front of each item in the list
 Number placed against an item depends on the location of the item in the list.
 Example:
<body>
<ol>
<li>INDIA</li>
<li>SRILANKA</li>
</ol>
</body>

 To start an ordered list at a number other than 1, use START attribute:


Example : <ol start=11>

• Select the type of numbering system with the type attribute. Example:
o A-Uppercase letters. <OL TYPE=A>
o a-Lowercase letters. <OL TYPE=a>
o I-Uppercase Roman letters
o i-Lowercase Roman letters
o 1-Standard numbers, default
7

Bulleted List (Unordered List)


• Example:
<ul>
<li>Latte</li>
<li>Expresso</li>
<li>Mocha</li>
</ul>

• To change the type of bullet used throughout the list, place the TYPE
attribute in the <UL> tag at the beginning of the list.
 DISC (default) gives bullet in disc form.
 SQUARE gives bullet in square form.
 CIRCLE gives bullet in circle form.

<ul>
<li type=‘disc’>Latte</li>
<li type=‘square’>Expresso</li>
<li type=‘circle’>Mocha</li>
</ul>
8

Adding Image
• Images are added into a document using <img> tag.
• Attributes of <img> tag are:
 alt: Alternative text to display for non-graphical browsers.
 align: Image horizontal alignment. Valid values: left, right, center.
 width/Height: Sets the width and height of the image.
 src: Specifies the image path or source.
9

Table
• Use <table> tag to create a table.
• Table Attributes:
 Border: <table border=“2”>………</table>
 Align: defines the horizontal alignment of the table element.
o Values of the align attribute are right, left and center. <table align=“center”>
 Width: defines the width of the table element.
o <table width=“75%”>………</table>
o <table width=“400”>………</table>
• Example:
<table border="1">
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
10

Table Data
• An HTML table has two kinds of cells:
 Header Cells <th>: Contain header information (created with <th> element) ;
The text is bold and centered.
 Standard Cells <td>: Contain data (created with the td element) ; The text is
regular and left-aligned.

<table>
<tr> <th>Column1 Header</th> <th>Column2 Header</th></tr>
<tr> <td>Cell 1,1</td> <td>Cell 1,2</td> </tr>
<tr> <td>Cell 2,1</td> <td>Cell 2,2</td> </tr>
</table>

• You can insert a bgcolor attribute in a <table>, <td>, <th> or <tr> tag to
set the color of the particular element.
<table bgcolor="cyan">
<tr bgcolor="blue">
11

Cell Spanning
• colspan="number of columns"
• rowspan="number of rows"
 Forces a table cell to span the number of rows specified by the given value.

<table border=1>
<tr> <th>Column 1</th><th>Column 2</th><th>Column 3</th> </tr>
<tr>
<td rowspan=2>Column 1 Data</td>
<td align=center colspan=2>Col 2, Row 1 Data</td>
</tr>
<tr> <td>Col 2, Row 2 Data</td><td>Col 3, Row 2 Data</td>
</tr>
</table>
12

How Does a Hyperlink Work?


• Hyperlinks access resources on the internet.
 Create a link with <a href=“”> (anchor)

 <a href="http://www.mysite.com/login.htm">Login Here</a>


 Hello, Welcome to <a href="welcome.htm">My Site</a>
 I have some <a href="http://www.state.edu/info/info.htm"> information</a> about this

• Links to Specific Part of a Page


 Name attribute, used in the anchor tag, identifies a section of a page.
o Precede name with a # symbol to differentiate it from the name of another document
<A NAME=”section1”></A>
< -- Text of section 1-- >
You find the relevant information in <A HREF=”#section1”>section 1</A>.

 For documents located on other computers, attach the section name, preceded
by the # symbol, at the end of the document URL. Eg:
o I am working in <a ref=“http://www.state.edu/docs/add.htm#address1”>ABC</A>
 To include a link to the named section from another local document :
o Please find relevant info in <A HREF=”report.htm#section1”>section 1</A>
13

Links to E-Mail
• “mailto” URL tag identifies the address to which an e-mail is to be sent
 If the link is selected, the browser starts an email program to send a message
to the recipient listed in the URL.
 Send me <A HREF=”mailto:abc@bcsbom.abc.com?subject=Mycomments”>
e-mail </A>with your comments about my page.<br>
 <a href=“mailto:dude@abc.com?subject=More Info”>Contact Me</a><br>
 Please <a href=“mailto:author@abc.com>mail</a> your comments to me.

• CC and BCC in Email

<body> <!----add the CC and BCC's--->


<a href="mailto:Ri@domain.com?
Subject=Hi&cc=jane@domain.com&bcc=joe@domain.com"> Email me</a>
</body>
14

Frame Basics
• Frames are created with <FRAMESET> and <FRAME> tags.
 Don’t use <body></body> tags with <frameset> </frameset> tags.
• <Frameset> tag has two attributes: <frameset rows=“50%, 25%, 25%”>
<frameset rows=“150, *”>
rows and cols <frameset cols=“40%, *”>
• <Frame> : defines a frame within a frameset. Attributes :
 src=“url”
 name=“window_name” : optional
 scrolling=“yes/no/auto” : “auto” displays a scrollbar when needed; is default
 [noresize] <html>
<head> </head>
<frameset rows=10%,*>
<frame border=0 name=top src="top.html" noresize scrolling=no>
<frameset cols=20%,*>
<frame name=left src="Left.html">
<frameset rows=70%,*>
<frame name=main src="Main.html">
<frame name=details src="about:blank">
</frameset>
</frameset>
</frameset>
</html>
15

HTML Forms : Types of Form Fields


<form method=“get/post” action=“URL”>
Field definitions
</form>

• <input> tag is used to create form input fields.


 Type attribute of <input> tag specifies the field type
o Single line text box <input type=“text”>
o Password field <input type=“password”>
o Hidden field <input type=“hidden”>
o Radio button <input type=“radio”>
o Checkbox <input type=“checkbox”>
o File selector dialog box <input type=“file”>
o Button <input type=“button”>
o Submit/Reset <input type=“submit/reset”>
• <textarea>
• <select>
• <button>
16

Text Field
• Single Line Text Fields: used to type letters, numbers, etc. in a form.
<INPUT TYPE=”type” NAME=”name” SIZE=”number” VALUE=”value” maxlength=n>
 Eg: <form>
First name: <input type="text" name="firstname“ value=“fname>
Last name:<input type="text" name="lname">
</form>

• Text Area (Multiple Line Text Field)


 A text area can hold an unlimited number of characters. Text renders in a fixed-
width font (usually Courier).
 You can specify text area size with cols and rows attributes.
<textarea name=“name” rows=“10” cols=“50” [disabled] [readonly]>
Default-Text
</textarea>
<textarea name=“address” rows=5 cols=10>
Please write your address
</textarea>
<textarea rows=“4” cols=“20”>
17

Check Box
• Lets you select one or more options from a limited number of choices.
<input type=“checkbox” name=“name” value=“value” [checked]
[disabled]> Checkbox Label
 Content of value attribute is sent to the form's action URL.

<input type=“checkbox” name=“color1” value=“0”/>Red


<input type=“checkbox” name=“color3” value=“1” checked/>Green

Radio Buttons
<input type=“radio” name=“name” value=“value” [checked] [disabled]>
Radio Button Label
• Content of the value attribute is sent to the form's action URL.

<form>
<input type="radio" name="sex" value="male"/>Male<br>
<input type="radio" name="sex" value="female"/> Female
</form>
18

Password Fields
• <input type=“password” name=“name” size=n value=“value” [disabled]>
 Eg: Enter the password:<input type=“password” name=“passwd” size=20
value=“abc”>

Hidden Field
• Allows to pass information between forms:
• <input type=“hidden” name=“name” size=“n” value=“value”/>
• <input type=“hidden” name=“valid_user” size=“5” value=“yes”/>

File Selector Dialog Box


• <input type=“file” name=“name” size=“width of field” value=“value”>
<FORM>
Please select file that you want to upload:
<INPUT name=“file” type=“file”> <BR>
<INPUT type=“submit” >
</FORM>
19

Action Buttons
• To add a button to a form use:
 <input type=“button” name=“btnCalculate” value=“Calculate”/>
• To submit the contents of the form use:
 <input type=“submit” name=“btnSubmit” value=“Submit”/>
• To reset the field contents use:
 <input type=“reset” name=“btnReset” value=“Reset”/>
• You can also create button using <button> tag ; defines a push
button. <button type="button">Click Me!</button>

Drop-Down List
<select name=“name” multiple=“true/false” size=n [disabled]>
<option [selected] [disabled] [value]>Option 1</option>…
</select>
 Multiple: States if multiple element selection is allowed.
 Size: Number of visible elements.
 Disabled: States if the option is to be disabled after it first loads.
Introduction to HTML5 Enhanced Form Elements
• A Form is one of the most basic and essential feature of any web site
 HTML5 brings 13 new input types
 HTML5 introduces these data types via the <input
type=”_NEW_TYPE_HERE_”/> format
• In many cases, on a mobile device, changing the input type will also
cause the device to put up a custom keyboard to enable the user to
enter the right kind of data.

• HTML5 Attributes for <input>


 Placeholder - A placeholder is a textbox that hold a text in lighter shade
when there is no value and not focused
 AutoFocus - Autofocus is a Boolean attribute of form field that make browser
set focus on it when a page is loaded
 Required - A "Required Field" is a field that must be filled in with value
before submission of a form
New Form elements
• Email - This field is used to check whether the string entered by the user
is valid email id or not.
 <input id="email" name="email" type="email" />
• Search - used for search fields (behaves like a regular text field).
 <input id="mysearch" type="search" />
• Tel - used for input fields that should contain a telephone number.
 <input type="tel" name="usrtel">
• url - is used for input fields that should contain a URL address.
 Depending on browser support, the url field can be automatically validated
when submitted.
• color – displays a color palette
• Number - used for input fields that should contain a numeric value.
 <input id="movie" type="number" value="0"/>
 <input type="number“ min="0“ max="50“ step="2“ value="6">
• Range - used for input fields that should contain a value within a range
New Form elements
• Date - used for input fields that should contain a date.
 Depending on browser support, a date picker can show up in the input field.
 <input id="meeting" type="date“ />
• month - Selects month and year
• week - Selects week and year
• time - Selects time (hour and minute)
• datetime - Selects time, date, month and year
• datetime-local - Selects time, date, month and year (local time)
• Data List - specifies a list of options for an input field. The list is created
with option elements inside the datalist
Audio & video
• HTML5 specifies a standard way to include audio, with the audio
element; The audio element can play sound files, or an audio stream.
 Other properties like auto play, loop, preload area also available

<audio controls>
<source src="vincent.mp3" type="audio/mpeg"/>
<source src="vincent.ogg" type="audio/ogg"/>
</audio>

• HTML5 specifies a standard way to include video with the video


element
 Supported video formats for the video element : Ogg, MP4, WebM, .flv, .avi
 Attributes : width, height, poster, autoplay, controls, loop, src

<video controls="controls" width="640" height="480" src=“bunny.mp4" />


Your browser does not support the video element.
</video>
Canvas
• A canvas is a rectangle in your web page within which you can use
JavaScript to draw shapes
 Canvas can be used to represent something visually in your browser like
Simple Diagrams, Fancy user interfaces, Animations, Charts and graphs,
Embedded drawing applications, Working around CSS limitations
 The canvas element has no drawing abilities of its own. All drawing must
be done inside a JavaScript

<canvas id="myCanvas" width="200" height="100">


</canvas>

<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
ctx.fillStyle='#FF0000';
ctx.fillRect(0,0,80,100);
</script>
New Semantic Elements
• <section> : can be used to thematically group content
• <article>: represents a self-contained composition in a document, page,
application, or site that can be independently distributable or reusable
 Eg a forum post, a magazine or newspaper article, a blog entry, a user comment
• <nav>: Represents a major navigation block. It groups links to other pages
or to parts of the current page.
• <Header>: tag specifies a header for a document or section. Can also be
used as a heading of an blog entry or news article as every article has its
title and published date and time
• <aside>: is a section that somehow related to main content, but it can be
separate from that content header and footer element in an article.
• <footer>: Similarly to "header" element, "footer" element is often referred
to the footer of a web page.
 However, you can have a footer in every section, or every article too
• <figure>: The <figure> tag specifies self-contained content,
like illustrations, diagrams, photos, code listings, etc.
Using the Geolocation API
• geolocation is best described as the determination of the geographic
position of a person, place, or thing
 Geolocation API is used to locate a user's position
• Test for the presence of the geolocation object:
if (navigator.geolocation) // check for Geolocation support
console.log('Geolocation is supported!');
else console.log('Geolocation is not supported for this Browser/OS version yet.');

• Obtain the geolocation object var geolocation = navigator.geolocation;


 Geolocation object Methods
o getCurrentPosition() : retrieves the current geographic location of the user.
o watchPosition() : retrieves periodic updates about the current geographic location of
the device.
o clearWatch() : cancels an ongoing watchPosition call.

function getLocation() {
var geolocation = navigator.geolocation;
geolocation.getCurrentPosition(showLocation, errorHandler);
}
Using the Geolocation API
• getCurrentPosition() method is called asynchronously with an object
Position which stores the complete location information.
 The Position object specifies the current geographic location of the device

function showLocation( position ) {


var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
...
}

 We need to catch any error and handle it gracefully


28

CSS Syntax
• A CSS rule has two parts: a selector, and one or more declarations:

• "HTML tag" { "CSS Property" : "Value" ; }


29

Three Ways to Insert CSS


• Embedded Style Sheets
 Style defined between <STYLE>..</STYLE> tags. <STYLE> tags appear
either in <HEAD> section or between </HEAD> and <BODY> tags.

• Linked Style Sheets


 Separate files (extn .CSS) that are linked to a page with the <LINK> tag. Are
referenced with a URL. Placing a single <LINK> tag within the <HEAD> tags
links the page that needs these styles.
 <head> <link rel="stylesheet" type="text/css" href="mystyle.css"> </head>

• Inline Style Sheets


 Only applies to the tag contents that contain it. Used to control a single tag
element. Tag inherits style from its parent. Egs.
 <p style="color:sienna;margin-left:20px">This is a paragraph.</p>
 <p style="background: blue; color: white;">A new background and font color
with inline CSS</p>
30

Demo: Link Style Sheet


<html> body { background: black;
<head> color:green
<link rel=stylesheet href=“linked_ex.css” }
type=“text/css”> h1 { background: orange;
</head> font-family: Arial, Impact;
<body> color: blue;
<h2>This is Level 2 Heading, with style</h2> font-size:30pt;
<h1>This is Level 1 Heading, with style</h1> text-align: center
<h3>This is Level 3 Heading, with style</h3> }
<h4>This is Level 4 Heading, without style</h4> h2, h3 { background: gold;
</body> font-family: Arial, Impact;
</html> color:red }
31

Inline Style Sheet


• All style attribute are specified in the tag it self. It gives desired effect on
that tag only. Doesn’t affect any other HTML tag.
<body style="background: white; color:green">
<h2 style="background: gold; font-family: Arial, Impact; color:red">
This is Level 2 Heading, with style</h2>
<h1 style="background: orange; font-family: Arial, Impact; color: blue;font-
size:30pt; text-align: center">This is Level 1 Heading, with style</h1>
<h3 style="background: gold; font-family: Arial, Impact;color:red">
This is Level 3 Heading, with style</h3>
<h4>This is Level 4 Heading, without style</h4>
<h1>This is again Level 1 heading with default styles</h1>
</body>
Grouping Selectors
• In style sheets there are often elements with the same style.
 H1 { color:green; }
 h2 { color:green; }
 P { color:green; }
• To minimize the code, you can group selectors by separating each
selector with a comma. Example
 h1,h2,p { color:green; }

Types of selectors
• HTML selectors
 Used to define styles associated to HTML tags. – already seen!!!!
• Class selectors
 Used to define styles that can be used without redefining plain HTML tags.
• ID selectors
 Used to define styles relating to objects with a unique id
ID Selector <style>
H1.myClass {color: blue}
& Style .myOtherClass { color: red; text-align:center}
Sheet </style>
<body style="background: white; color:green">
Classes <H1 class="myClass">This text would be blue</H1>
<p class="myOtherClass">The text would be in red</P>
<H3 class="myOtherClass">This is level 2 heading</H3>
<table class=myotherClass border width=100%>
<html> <head>
<td>Data 1</td><td>Data 2</td></table>
<style>
<h3>This is Level 4 Heading, without style</h3>
#para1 {
<h1>This is again Level 1 heading with default styles</h1>
text-align:center;
color:red;
}
</style> </head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the
style.</p>
</body>
</html>
CSS Box Model
• All HTML elements can be considered as boxes.
• The CSS box model is essentially a box that wraps around HTML
elements, and it consists of:
 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 images appear
CSS Border
• The border property is a shorthand for the following individual border
properties: border-width, border-style (required), border-color
p { border: 5px solid red; }
Introduction to Javascript
Embedding JavaScript in HTML
• The <SCRIPT> tag <SCRIPT>
JavaScript statements …
</SCRIPT>
<html>
<head> </head>
<body>
<script type="text/javascript">
document.write("<H1>Hello World!</H1>")
</script>
</body>
</html>

• Where to Write JavaScript?


 Head Section
 Body Section
 External File
Data Types in JavaScript
• JavaScript is a free-form language. Need not declare all variables,
classes, and methods
• Variables in JavaScript can be of type:
 Number (4.156, 39)
 String (“This is JavaScript”)
 Boolean (true or false)
 Null (null)  usually used to indicate the absence of a value

• Defining variables. var variableName = value


• JavaScript variables are said to be un-typed or loosely typed
 letters of the alphabet, digits 0-9 and the underscore (_) character and is
case-sensitive.
 Cannot include spaces or any other punctuation characters.
 First character of name must be either a letter or the underscore character.
 No official limit on the length of a variable name, but must fit within a line.
Javascript operators:
Control Structures and Loops
• JavaScript supports the usual control structures:
 the conditionals:
o if, if(condition) { if(a>10) {
o if...else statement 1 document.write(“Greater than 10”)
o If … else if … else
} else { } else {
statement 2 document.write(“Less than 10”)
o Switch
} }

document.write( (a>10) ? “Greater than 10” : “Less than 10” );


 iterations:
switch (variable) {
o for
case outcome1 :{
o while //stmts for outcome 1
break; }
case outcome2 :{
//stmts outcome 2
break; }
default: {
//none of the outcomes is chosen
}
}
for Statements
2.3: Control Structures and Loops

for( [initial expression;][condition;][increment expression] )


{ statements
}

for(var i=0;i<10;i++)
{
document.write(“Hello”);
}

The while Statement


while(condition) { while(i<10) {
statements document.write(“Hello”);
} i++;
}

Break & Continue Statements


JavaScript Functions
function myFunction (arg1, arg2, arg3) Calling the function :
{ myFunction( “abc”, “xyz”, 4 )
statements myFunction()
return
}

function area(w1, w2, h) { function diameter(radius){


var area=(w1+w2)*h/2; return radius * 2;
alert(area+" sq ft"); }
}
area(2,3,7); //calling the function var d=diameter(5); //calling the function

• Function expressions - functions are assigned to variables

var myFunction = function() { var area = function (radius) {


statements return Math.PI * radius * radius;
} };
alert(area(5)); // => 78.5
Global and Local Variables
<script language=“Javascript”>
var companyName=“TechnoFlo”
function f(){
var employeeName=“Henry”
document.write(“Welcome to ”+companyName+ ”, “ +employeeName)
}
</script>

• Variables that exist only inside a function are called Local variables
• Variables that exist throughout the script are called Global variables
 Their values can be changed anytime in the code and even by other functions
Predefined Functions
• isFinite: evaluates an argument to determine if it is a finite number.
isFinite (number) //where number is the number to evaluate

• isNaN : Evaluates an argument to determine if it is “NaN” (not a number)


o isNaN (testValue), where testValue is the value you want to evaluate
• Parseint and parsefloat
 Returns a numeric value for string argument.
 parseInt (str)
 parseFloat (str)

2.4: JavaScript Functions


Working with Predefined Core Objects
Lesson 10. Cascading Style Sheets
46

String Objects
• Creating a string object:
 var myString = new String(“characters”)
 var myString = “fred”

• Properties of a string object:


 length: returns the number of characters in a string.

• “Lincoln”.length // result = 7
• “Four score”.length // result = 10
• “One\ntwo”.length // result = 7
• “”.length // result = 0
47

String functions
• charAt(index) : returns the character at a specified position.
 Eg : var str = "Hello world!";
o str.charAt(0); //returns H
o str.charAt(str.length-1)); //returns !
• concat() : joins two or more strings
 stringObject.concat(stringX,stringX,...,stringX)
 Eg: var str1="Hello ";
var str2="world!";
document.write(str1.concat(str2));
• indexOf () : returns the position of the first occurrence of a specified
string value in a string.
 index values start their count with 0.
 If no match occurs within the main string, the returned value is -1.
 string.indexOf( searchString [, startIndex])
Eg : var str="Hello world, welcome";
str.indexOf("Hello"); //returns 0
str.indexOf("wor")); //returns 6
str.indexOf("e",5); //returns 14
48

String Objects
• match(regExpression) var str="rain in SPAIN is mainly in plain";
 Searches for a specified value in a string var patt1=/ain/gi;
document.write(str.match(patt1));
 string.match(regExpression)
• replace(regExpression, replaceString)
 Replaces some characters with some other characters in a string.
 string.replace( regExpression, replaceString)
 Eg: var str=“Hello World";
document.write(str.replace(“World", “Everyone"));
• search(regExpression)
var str = “To be, or not to be”
 Searches a string for a specified value
var regexp = /be/
 Eg : var str=“Hello World"; str.relace(regexp, “exist”)
str.search("World") //returns 6
var text = "testing: 1, 2, 3"; // Sample text
var pattern = /\d+/g // Matches all instances of one or more digits
text.search(pattern) // => 9: position of first match
Eg: text.match(pattern) // => ["1", "2", "3"]: array of all matches
text.replace(pattern, "#"); // => "testing: #, #, #"
49

String functions
• split(“delimiterCharacter”[, limitInteger]) - Splits a string into array of strings
 string.split(“delimiterCharacter”[, limitInteger]) Output :
zero
var str = "zero one two three four";
one
var arr = str.split(" ");
two
for(i = 0; i < str.length; i++){ document.write(“<br>” + arr[i]); }
three
var myString = “Anderson,Smith,Johnson,Washington” four
var myArray = myString.split(“,”)
var itemCount = myArray.length // result: 4

• toLowerCase() / toUpperCase() Eg: var str="Hello World!";


str.toLowerCase() //returns hello world
• slice( startIndex [, endIndex]) str.toUpperCase() //returns HELLO WORLD
 Extracts a part of a string and returns the extracted part in a new string

Eg : var str=“Hello World";


str.slice(6) //returns World
str.slice(0,1) //returns H
50

Date
• Date object allows the handling of date and time information.
 All dates are in milliseconds from January 1, 1970, 00:00:00.
 Dates before 1970 are invalid dates.
• There are different ways to define a new instance of the date object:

var d = new Date() //Current date


var d = new Date(milliseconds)
var d = new Date(dateString)
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds)

<script>
var d=new Date();
document.write(d);
</script>

var d = new Date(86400000);


var d = new Date(99,5,24,11,33,30,0);
Date Object - Methods
• getDate( ) Date of the month (1 - 31)
• getDay( ) Day of the week (0 - 6, 0-Sunday)
• getMonth( ) The month (0 - 11, 0 - Jan.)
• getFullYear( ) The year (4 digits)
• getHours( ) Hour of the day (0 - 23)
• getMinutes( ) Minutes (0 - 59)
• getSeconds( ) Seconds (0 - 59)
• getTime( ) Milliseconds since 1/1/1970
• getTimezoneOffset( ) Offset between local time and GMT
• setDate(dayValue) 1-31
• setHours(hoursValue) 0-23
• setMinutes(minutesValue) 0-59
• setMonth(monthValue) 0-11
• setSeconds(secondsValue) 0-59
• setTime(timeValue) >=0
• setYear(yearValue) >=1970
52

Array
• An array is data structure for storing and manipulating ordered
collections of data.
• An array can be created in several ways.
 Eg1: Regular: ----------------------------------------- var cars=new Array();
cars[0]="Spark";
 Eg 2: Condensed: cars[1]="Volvo";
o var cars=new Array("Spark","Volvo","BMW"); cars[2]="BMW";
 Eg 3: Literal:
o var cars=["Spark","Volvo","BMW"];
 Eg 4: var matrix = [[1,2,3], [4,5,6], [7,8,9]];
 Eg 5 : var sparseArray = [1,,,,5];

• Deleting an array element eliminates the index from the list of


accessible index values
 delete is a unary operator that attempts to delete myArray.length// result: 5
the object property or array element specified delete myArray[2]
 This does not reduce array’s length myArray.length// result: 5
myArray[2] // result: undefined
53

Array Object Methods


 arrayObject.reverse()
 arrayObject.slice(startIndex, [endIndex])
 arrayObject.join(separatorString) : array contents will be joined and placed
into arrayText by using the comma separator“
 arrayObject.push(): add one or more values to the end of an array

arrayObject.slice(startIndex [, endIndex]) //Returns: Array


var solarSys = new Array (“Mercury”,”Venus”,”Earth”,”Mars”,”Jupiter”,”Saturn”)
var nearby = solarSys.slice(1,4)
// result: new array of “Venus”, “Earth”, “Mars”

arrayObject.concat(array2)
var arrayText = myArray.join(“,”)
var a1 = new Array(1,2,3)
var a2 = new Array(“a”,”b”,”c”)
var a3 = a1.concat(a2)
// result: array with values 1,2,3,”a”,”b”,”c”

a = []; // Start with an empty array


a.push("zero") // Add a value at the end. a = ["zero"]
a.push("one", "two") // Add two more values. a = ["zero", "one", "two"]
Creating New Objects
1. Using Object Initializers
 Syntax : objName = {property1:value1, property2:value2, … }
 person = { "name ":"amit", "age":23};
 myHonda = {color:“red”, wheels:4, engine:{cylinders:4, size:2}}
2. Using Constructors
 Define the object type by writing a constructor function.
 Create an instance of the object with new.

function car(make, model, year) { function person(name, age) {


this.make = make this.name = name
this.model = model this.age = age
this.year = year }
} ken = new person( “Ken” , 33 )
…..
mycar = new car( “Ford” , “Mustang” , 2013) function car(make, year, owner) {
this.make = make
this.year = year
this.owner = owner
}
car1 = new car( “Mazda”, 1990, ken )
Creating New Objects (Contd.)
• Accessing properties
car2.owner.name car1.make = “corvette”
• Defining methods
obj.methodName = function_name
 Example: obj.methodName(params)

function car(make, model, year, owner) {


this.make = make;
this.model = model;
this.year = year;
this.displayCar = displayCar;
}
function displayCar() {
document.writeln( “A beautiful” + this.year
+ “ ” + this.make + “ ” + this.model
}
….
car1.displayCar(); car2.displayCar()
Examples : Using Object Initializers
57

JavaScript Document Object Model


58

Window Object Methods


• alert(message)
 window.alert(“Display Message”)
• confirm(message)
 window.confirm(“Exit Application ?”)
• prompt(message,[defaultReply])
 var input=window.prompt(“Enter value of X”)

• window.open(URL,name,specs)
 URL : Specifies the URL of the page to open. If no URL is specified, a new
window with about:blank is opened
 Name : Specifies the target attribute or the name of the window.
 Specs : comma-separated list of items.
example opens an
myWindow=window.open('','','width=200,height=100'); about:blank page in a new
myWindow.document.write("<p>This is 'myWindow'</p>"); browser window:
myWindow.focus();
59

setInterval and setTimeout methods


Document Object
 When an HTML document is loaded into a web browser, it becomes a
document object; root node of the HTML document and owns all other nodes
Examples : Modifying content
Example : Modifying styles
Mouse events
Form validation
Example
Example
Example
XML
69

A Sample XML Code


<?xml version="1.0"?>
<BOOK>
<TITLE>King of the Murgos</TITLE>
<AUTHOR>Eddings, David</AUTHOR>
<PUBLISHER>Del Ray</PUBLISHER>
<COVER TYPE="PAPERBACK" />
<CATEGORY CLASS="FANTASY" />
<ISBN>0-345-41920-0</ISBN>
<RATING NUMBER="5" />
<COMMENTS>Book 2 of the Malloreon. </COMMENTS>
</BOOK>

• Different parts of the XML file:


 XML Declaration: It is a processing instruction
 Root Element::Each XML document must have only one root element, all the
other elements must be completely enclosed in that element.
 An Empty Element: is an element that may not have any content.
 Attributes:
o one or more; optional or mandatory.
Well Formed XML Documents
• An XML document with correct syntax is "Well Formed".
• The syntax rules:
 must begin with the XML declaration <?xml version="1.0"?>
 XML documents must have a root element <Employee>
<ECode>1111</ECode>
 XML elements must have a closing tag
<Ename>
 XML tags are case sensitive <Fname>Neeta</Fname>
 If an element is empty, it still must be closed. <Lname>Singh</Lname>
</Ename>
 XML elements must be properly nested
<Desig desigId="4"/>
 XML attribute values must be quoted <Salary> 21000 </Salary>
</Employee>
Valid XML
• Well-formed vs. Valid : "well formed" XML document is not the same as a
"valid" XML document.
• A "valid" XML document must be well formed. In addition, it must conform
to a document type definition.
• There are 2 different document type definitions that can be used with XML:
 DTD - The original Document Type Definition
 XML Schema - An XML-based alternative to DTD
• Validation of XML is always done against DTD / Schema by Parser
• Parser is a program that parses XML document & occasionally modifies it.
 Various parsers are available in market along with XML editors Eg. Altova
XMLSpy, Eclipse, MSXML Parser, Expat XML parser etc.
• XML Parsers can be classified as
 Non Validating Parsers - Only checks for structure problems in the code
o sufficient when there is no DTD or schema linked to the XML code; Most browsers
 Validating Parsers - Checks for validation rules specified in DTD or Schema
XML DTD (Document Type Declaration)
• DTD defines the structure of an XML document.
 It defines the structure with a list of legal elements
 A DTD can be declared inside an XML document or in an external file.
• Internal DTD: is wrapped inside the <!DOCTYPE> definition. Syntax:
o <!DOCTYPE root-element [element declarations]>
XML DTD
• External DTD Declaration
 DTD is declared in an external file; the <!DOCTYPE> definition must contain a
reference to the DTD file
 Syntax: <!DOCTYPE root-element SYSTEM “filename”>
74

Using DTD : Working with Elements and Attributes


• Element Declarations: First declaration inside a DTD
 syntax: <!ELEMENT name content> ;where “name” is a standard XML name
• Empty Elements: have no content &are marked up as either :
o <empty_element/>
o <empty_element></empty_element>
 Eg : <!ELEMENT empty_element EMPTY>
• Elements with Parsed Character Data : Elements with only parsed
character data are declared with #PCDATA inside parentheses:
• <!ELEMENT element-name (#PCDATA)>
• Unrestricted Elements: Opposite of an empty element
o An unrestricted element can contain any element that is declared elsewhere in the
XML document’s DTD.
 An unrestricted element’s content is declared as follows:
o <!ELEMENT any_element ANY>
75

Working with Elements and Attributes


• Element Sequences:
 It is a simplest form of element content model - a list of the possible elements,
enclosed in parentheses and separated by commas.
 Example:
<counting>
o <!ELEMENT counting (first, second, third, fourth)> <first>one</first>
<second>Two</second>
….
</ counting>
• Element Choices:
 A choice of elements in an element content model is indicated by a vertical
line ( | ) between the alternatives, as shown below:
o <!ELEMENT choose (this_one | that_one)>
 Example: <choose>
<this_one> choose this one</this_one>
</choose>
and then
<choose>
<that_one>chose that one</that_one>
</choose>
76

Working with Elements and Attributes


• Combined Sequences and Choices:
 Content sequence & choices can be combined by grouping the element
content into model groups.
 For example:
!ELEMENT lots_of_choice (may_be | could_be), (this_one, that_one)>

o The “lots_of_choice” element can consist of either a may_be element or a


could_be element; followed by this_one element & then that_one element.

• Element Occurrence Indicators: specify how many times elements


can appear
 The ? character indicates that the element or group of elements may be
omitted or may occur just once.
 The * character indicates that an element or group of elements may be
omitted or may appear zero or more number of times.
 The + character indicates that an element or group of elements must
appear at least once and may appear one or more number of times.
77

Working with Elements and Attributes


• Character Content
 # PCDATA (Parsed Character data) in the content model
 Text is allowed in the element
 Eg declarations:
o <!ELEMENT para (title, text)>
o <!ELEMENT title (#PCDATA)>
o <!ELEMENT text (#PCDATA)> <para>
 XML document could look like :
<title>My Life</title>
<text>My life is full of joy</text>
</para>
• Mixed Content Elements:
 Elements that can contain text, elements, or both are called “mixed content
models”:
o <!ELEMENT pick (#PCDATA | aaa | bbb | ccc | ddd)*>
78

Working with Elements and Attributes


• Attribute Declaration: attributes are declared with an ATTLIST declaration
 You can declare one element at a time.
 Elements can have lots of attributes.
 Attributes are all declared at once in an attribute declaration list.
 An attribute declaration list has the following form:

<!ATTLIST element-name attribute-name attribute-type attribute-value>

 The attribute-type can be one of the following:


Type Description
CDATA The value is character data
(en1|en2|..) The value must be one from an enumerated list
ID The value is a unique id
IDREF The value is the id of another element
NMTOKEN The value is a valid XML name
NMTOKENS The value is a list of valid XML names
ENTITY The value is an entity
ENTITIES The value is a list of entities
Working with Elements and Attributes .:Egs
• The attribute-value can be one of the following:

Value Explanation
value The default value of the attribute
#REQUIRED The attribute is required
#IMPLIED The attribute is optional
#FIXED value The attribute value is fixed

DTD: <!ATTLIST person number CDATA #REQUIRED>


Valid XML: <person number="5677" />
Invalid XML: <person />

DTD: <!ATTLIST contact fax CDATA #IMPLIED>


Valid XML: <contact fax="555-667788" />
Valid XML: <contact />

DTD: <!ATTLIST sender company CDATA #FIXED “Abc">


Valid XML: <sender company=“Abc" />
Invalid XML: <sender company=“Xyz" />
Working with Elements and Attributes
• Default Attribute Value
 DTD: <!ELEMENT square EMPTY>
 Valid XML:
<!ATTLIST square width CDATA "0">
<square width="100" /> If no width specified, has a default value of 0

• Enumerated Attribute Types:


 They have values that are simply lists of possible values.
 Each value has to be a valid name token (NMTOKEN).

Enumerated attrs syntax:


<!ATTLIST element-name attribute-name (en1|en2|..) default-value>
DTD: <!ATTLIST payment type (check|cash) "cash">
XML example: <payment type="check" /> Value given in quotes
Or <payment type="cash" /> is a default value for
Invalid XML : <payment type=“EFT” /> this attribute.

 Eg:
<!ATTLIST paint color (RED | YELLOW | GREEN ) “RED”>
81

Working with Elements and Attributes


• IDREF:
 This attribute is a pointer to an ID (an ID reference).
 Its value must match the value of an ID type attribute that is declared
somewhere in the same document.
 Usage: <!ATTLIST emp deptno IDREF>

<emp deptno=”D10”>

• IDREFS:
 The value of this attribute consists of one or more IDREF type value,
separated by spaces.
 IDREFS type declaration : <!ATTLIST seminar departments IDREFS>

 Usage: <seminar departments=” D10 D20 D30”>


Working with Entities
• Entities are used to define shortcuts to special characters.
 Entities can be declared internal or external.
 Internal Entity: Syntax : <!ENTITY entity-name "entity-value">
 External Entity : Syntax : <!ENTITY entity-name SYSTEM "URI/URL">

<!ENTITY writer SYSTEM "http://www.mytutorials.com/entities.dtd">


<!ENTITY copyright SYSTEM "http://www.mytutorials.com/entities.dtd">
XML example: <author>&writer;&copyright;</author>

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Shrilata T.">
<!ENTITY copyright "Copyright: MyTutorials.">
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>
DTD Example
XML Parser
• Simple API for XML (SAX)
 Also called as an event based parser
 Reads every element from the XML document, so whenever it encounters an
XML element or an error it generates and event.
 SAX is a memory efficient, fast & often used in high performance applications
 SAX works in serial access mode to parse XML document. .

• Document Object Model (DOM)


 Builds entire XML document structure in memory
 Standard way to access and manipulate XML documents using programming
languages
 DOM presents the XML document as a tree structure – with the elements,
attributes and text defined as nodes. You can access the information in the
XML documents in a hierarchical manner.
 Can be memory and CPU intensive so it is useful when the document is
small.
XML DOM
• XML DOM defines a standard for accessing & manipulating XML documents
 Ie, its a standard for how to get, change, add, or delete XML elements
 The DOM presents an XML document as a tree-structure
 In DOM, everything in an XML document is a node.
o The entire document is a document node
o Every XML element is an element node
o The text in the XML elements are text nodes
o Every attribute is an attribute node
Document
o Comments are comment nodes

Version Comment Element xdoc

<?xml version=”1.0”?>
<xdoc> Element greeting element farewell
<greeting>Hello XML</greeting>
<farewell>Goodbye HTML</farewell>
</xdoc> Text Text
The Node Object
• Represents a single node in the document tree.
 A node can be an element node, an attribute node, a text node
• Node Object Properties:

Property Description
A NamedNodeMap containing the attributes of this node (if it is an
attributes
Element)
childNodes Returns a NodeList of child nodes for a node
firstChild Returns the first child of a node
lastChild Returns the last child of a node
nextSibling Returns the node immediately following a node

nodeName Returns the name of a node, depending on its type


nodeType Returns the type of a node
nodeValue Sets/returns the value of a node, depending on its type
parentNode Returns the parent node of a node
previousSibling Returns the node immediately before a node
textContent Sets/returns the textual content of a node and its descendants
The Node Object

• Some Node Object Methods:


Method Description
appendChild() Appends a new child node to the end of the list of children of a node

hasAttributes() Returns true if the specified node has any attributes, else false

hasChildNodes() Returns true if the specified node has any child nodes, else false

insertBefore() Inserts a new child node before an existing child node

removeChild() Removes a specified child node from the current node


replaceChild() Replaces a child node with a new node
NodeList Object
• The NodeList object represents an ordered list of nodes.
 The nodes in the node list can be accessed through their index number
(starting from 0).
 The node list keeps itself up-to-date. If an element is deleted or added, in
the node list or the XML document, the list is automatically updated.
 Note: In a node list, the nodes are returned in the order in which they are
specified in the XML document.
• NodeList Object Property:
 length : Returns the number of nodes in a node list
• NodeList Object Method
 item() : Returns the node at the specified index in a node list
Implementing DOM
• For implementing DOM, you need an application that supports DOM.
• Some of the DOM engines are as follows:
 Microsoft DOM Engine : available in the latest MSXML.dll & as an ActiveX object
 IBM DOM Engines

• DOM using Javascript:


• Create an instance of the parser object and DOM engine:
 var xmlDoc;
 xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
• Load an XML file with the following syntax:
 xmlDoc.load("note.xml"); XML file will be parsed
as it is loaded. If any
• Load an XML string with the following syntax errors are found,
 xmlDoc.loadxml(string variable of xml file) loading will be aborted
Example output
Example
AJAX & JSON
Introduction
• JSON (JavaScript Object Notation), is a simple and easy to read and
write data exchange format.
 It is easy for humans to read and write.
 It is easy for machines to parse and generate.
 It is based on a subset of the JavaScript, Standard ECMA-262
 JSON is a text format that is completely language independent; can be
used with most of the modern programming languages.
 The filename extension is .json
 JSON Internet Media type is application/json
 It’s popular and implemented in countless projects worldwide, for those
don’t like XML, JSON is a very good alternative solution.
Values supported by JSON
• Strings : double-quoted Unicode, with backslash escaping
• Numbers: double-precision floating-point format in JavaScript
• Booleans : true or false
• Objects: an unordered, comma-separated collection of key:value pairs
• Arrays : ordered, comma-separated values enclosed in square brackets
• Null : A value that isn't anything
Demo
What is Ajax ?
• “Asynchronous JavaScript And XML”
 AJAX is not a programming language, but a technique for making the user
interfaces of web applications more responsive and interactive
 It provide a simple and standard means for a web page to communicate
with the server without a complete page refresh.

Why Ajax?
• Intuitive and natural user interaction
• No clicking required. Call can be triggered on any event
• Mouse movement is a sufficient event trigger
• "Partial screen update" replaces the "click, wait, and refresh" user
interaction model
• Only user interface elements that contain new information are updated (fast
response)
• The rest of the user interface remains displayed as it is without
interruption (no loss of operational context)
XMLHttpRequest
• JavaScript object - XMLHttpRequest object for asynchronously
exchanging the XML data between the client and the server
• XMLHttpRequest Methods
 open(“method”, “URL”, syn/asyn) : Assigns destination URL, method, mode
 send(content) : Sends request including string or DOM object data
 abort() : Terminates current request
 getAllResponseHeaders() : Returns headers (labels + values) as a string
 getResponseHeader(“header”) : Returns value of a given header
 setRequestHeader(“label”,”value”) : Sets Request Headers before sending
• XMLHttpRequest Properties
 Onreadystatechange : Event handler that fires at each state change
 readyState values – current status of request
 Status : HTTP Status returned from server: 200 = OK
 responseText : get the response data as a string
 responseXML : get the response data as XML data
Creating an AJAX application
• Step 1: Get an instance of XHR object
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

• Step 2: Make the request


xhr.open('GET', 'http://www.example.org/some.file', true);
xhr.send(null);

xhr.open("POST", "AddNos.jsp");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("tno1=100&tno2=200");

• Step 3 : Attach callback function to xhr object


httpRequest.onreadystatechange = function(){
// process the server response
};
Ajax Demo
AJAX Demo with XML
AJAX Demo with JSON
PHP (PHP: HYPERTEXT
PREPROCESSOR)
PHP intro
• PHP is a server scripting language, and a powerful tool for making
dynamic and interactive Web pages.
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use.
 was originally conceived by Rasmus Lerdorf in 1995.

• What is a PHP File?


 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the
browser as plain HTML
 PHP files have extension ".php“
Installing PHP
Basic PHP Syntax
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>:

<?php <?php
// PHP code goes here echo "<h1>Hello from PHP</h1>";
?> ?>

<!DOCTYPE html>
<html> A PHP file normally
<body> contains HTML tags,
<h1>My first PHP page</h1> and some PHP
<?php scripting code.
echo "Hello World!";
?>
</body>
</html>
// a single-line comment
# also a single-line comment
/*
• Comments in PHP : a multiple-lines comment block
 PHP supports several ways spanning multiple lines
*/
PHP Variables
• A variable starts with the $ sign, followed by the name of the variable
 PHP has no command for declaring a variable. It is created the moment you
first assign a value to it. Eg: $txt = "Hello world!";
$x = 5; echo "I love $txt!";
$y = 10.5; echo "I love " . $txt . "!";

<?php
• + is pure math operator: $x = "15" + 27;
$x = 5;
echo($x); //gives 42!!
$y = 4;
echo $x + $y;
• Rules for PHP variables:
?>
 Starts with the $ sign, followed by the name of the variable
 Must start with a letter or the underscore character only
 Can only contain alpha-numeric characters & underscores (A-z, 0-9, _ )
 Are case-sensitive ($age and $AGE are different)

Example, $popeye, $one and $INCOME are all valid PHP


variable names, while $123 and $48hrs are invalid.
Variables Scope
• Variables can be declared anywhere in the script.
• PHP has three different variable scopes:
 Local : can only be accessed within that function
 Global : can only be accessed outside a function
 Static : retains value of local variable even after function ends

<?php
$x = 5; // global scope
function myTest() {
echo "<p>Variable x inside function is: $x</p>"; // x inside function gives error
$y = 10; // local scope
echo "<p>Variable y inside function is: $y</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>"; // y outside function gives error
?>
Variables Scope
• The global Keyword
 used to access a global variable from within a function.
 To do this, use the global keyword before the variables (inside the function):

 PHP also stores all global variables in an array called $GLOBALS[index]. The
index holds the name of the variable. This array is also accessible from within
functions and can be used to update global variables directly
Variables Scope
• The static Keyword
 Normally, when a function is completed/executed, all of its variables are
deleted. However, sometimes we want a local variable NOT to be deleted.
We need it for a further job.
 To do this, use the static keyword when you first declare the variable

<?php
function myTest() {
static $x = 0;
echo $x; Note: The variable is still local
$x++; to the function.
}
Outputs : 0 1 2
myTest();
myTest();
myTest();
?>
Output data to the screen
• There are two basic ways to get output: echo and print

echo "<h2>PHP is Fun!</h2>";


echo “Hello <b>$name</b>!!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";

print "<h2>PHP is Fun!</h2>";


print "Hello world!<br>";
print "I'm about to learn PHP!";

• print_r() and var_dump() : dumps out PHP data - it is used mostly for
debugging
$stuff = array("name" => "Chuck", "course" => "SI664");
print_r($stuff);
Data Types
• PHP supports the following data types:
 String Eg - $x = "Hello world!";
 Integer Eg - $x = 5985;
 Float (floating point numbers - also called double) Eg $x = 10.365;
 Boolean Eg - $x = true;
 Array Eg - $cars = array("Volvo","BMW","Toyota");
 Object
 NULL
 Resource : are special variables that hold references to resources external to
PHP (such as database connections)
Example:
$handle = fopen("note.txt", "r"); $s1 = "";
var_dump($handle); $v1 = null;
$bool = false;
$no1 = 1;
• gettype(): Get the type of a variable echo ('$s1 : ' . gettype($s1) . "<br>");
echo ('$v1 : ' . gettype($v1) . "<br>");
echo ('$bool : ' . gettype($bool) . "<br>");
echo ('$no1 : ' . gettype($no1) . "<br>");
PHP Constants
• A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.
 A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
• To create a constant, use the define() function.
 Syntax : define(name, value, case-insensitive) //case: Default is false

<?php // Valid constant names


define("GREETING", "Welcome to PHP!"); define("ONE", "first thing");
echo GREETING; define("TWO2", "second thing");
?> define("THREE_3", "third thing")

• Constants are automatically global & can be used across the entire script


PHP Operators
• Arithmetic Operators
• Assignment Operators • Logical Operators
Operator Example Result Operator Example Meaning Operator Meaning
+ 4+2 6 += y += x y=y+x || or
- 4-2 2 -= y -= x y=y-x && and
* 4*2 8 *= y *= x y=y*x and and
/ 4/2 2 /= y /= x y=y/x or or
% 4%2 0 %= y %= x y = y % x xor xor
++ x = 4; x++; x=5 ! not
-- x = 4; x--; x=3

• Comparison Operators
• String Operators
Operator Meaning
Operator Example Result == is equal to
. $txt1 . $txt2 Concatenation of $txt1 & $txt2 != is not equal to
.= $txt1 .= $txt2 Appends $txt2 to $txt1 > is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
Conditional Statements : syntax
Conditional Statements : examples
Loops : syntax

Note : foreach() works only on


arrays, and is used to loop through
each key/value pair in an array
User Defined Functions
Functions function square(&$value) {
$value = $value * $value;
• Passing Parameters by Reference }
$a = 3;
square($a);
echo $a;

function getPreferences($whichPreference = 'all') {


//code that uses the parameter
• Default Parameters }

• Variable Parameters: PHP provides three functions you can use in the
function to retrieve the parameters passed to it.
 func_get_args() returns an array of all parameters provided to the function;
 func_num_args() returns the number of parameters provided to the function;
 func_get_arg() returns a specific argument from the parameters.

$array = func_get_args();
$count = func_num_args();
$value = func_get_arg(argument_number);
PHP include
• INCLUDE appends the code from an external file into the current file.
 Including files is very useful when you want to include the same PHP, HTML,
or text on multiple pages of a website
 Syntax : INCLUDE ("external_file_name");
Indexed Arrays
Associative Arrays
Multidimensional array Name Stock Sold
Volvo 22 18
• A multidimensional array is an array containing
BMW 15 13
one or more arrays
Saab 5 2
 Can be two, three, four, five, or more levels deep.
Land Rover 17 15
$cars = array( Table for
array("Volvo",22,18), this data data
array("BMW",15,13), Volvo: In stock: 22, sold: 18.
array("Saab",5,2), BMW: In stock: 15, sold: 13.
array("Land Rover",17,15) Saab: In stock: 5, sold: 2.
); Land Rover: In stock: 17, sold: 15. output

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";


echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

Nested for loop


Sorting Arrays
• array sort functions:
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key
Other array functions
• array_keys() : Return an array containing the keys
• array_pop() : deletes the last element of an array
• array_push() : inserts one or more elements to the end of an array
• array_values() : returns an array containing all the values of an array
• array_slice() : returns selected parts of an array. array_slice(array,start,length)
String Functions
Date Function

Eg : echo date("m/d/y"); // output : 04/10/13


echo date("l"); // Wednesday

Refer to http://php.net/manual/en/function.date.php for more


Date Function
• PHP core also provides a number of date and time; since they are
built in, you can use these functions directly within your script.
 date_create() : returns a new DateTime object.
 date_format() : returns a date formatted according to the specified format.
 getdate() : returns date/time info of a timestamp or current date/time.

$date=date_create("2013-03-15");
print_r($date);
//DateTime Object ( [date] => 2013-03-15 00:00:00.000000 [timezone_type] => 3
[timezone] => Europe/Berlin )
echo date_format($date,"Y/m/d H:i:s"); //2013/03/15 00:00:00

print_r(getDate()); //Returns an associative array of information


Array ( [seconds] => 31 [minutes] => 45 [hours] => 19 [mday] => 18 [wday] => 3 [mon]
=> 2 [year] => 2015 [yday] => 48 [weekday] => Wednesday [month] => February [0] =>
1424285131 )
Global Variables - Superglobals
$_SERVER Superglobal
 Holds information about headers, paths, and script locations
 Some of the most important elements that can go inside $_SERVER:
$_SERVER Demo
<?php
echo "Filename of executing script : " . $_SERVER['PHP_SELF'];
echo "Name of the host server : " . $_SERVER['SERVER_NAME'];
echo "Host header from the current request : " . $_SERVER['HTTP_HOST'];
echo "User agent : " . $_SERVER['HTTP_USER_AGENT'];
echo "Path of the current script : " . $_SERVER['SCRIPT_NAME'];
?>
$_POST and $_GET
• $_POST : used to collect form data after submitting an HTML form with
method="post".
<?php
$name = $_POST['fname']; // collect value of input field
if (empty($name)) echo "Name is empty";
else echo $name;
?>

• $_GET: used to collect form data after submitting an HTML form with
method="get“
<body>
<a href="test_get.php?fname=Anil&lname=Patil">Test $GET</a>
</body>
Mainpage.php

<body>
<?php echo "Study " . $_GET[‘fname'] . " at " . $_GET[‘lname']; ?>
test_get.php </body>
Form Handling ($_POST)
$_REQUEST
• Used to collect data after submitting an HTML form
Form Validation
• Isset() : Determine if a variable is set and is not NULL
 The isset() function returns TRUE, $s1 = isset($name); // $s1 is false
if the variable inside parentheses is set $name = "Fred";
$s2 = isset($name); // $s2 is true
Advanced form handling
• Multivalued Parameters in select element:
• HTML’s select tag allows multiple selections
 To process such multiple selection, you need to make the name of the field in
the HTML form end with []. Eg:

 Now, when the user submits the form, $_GET['languages'] contains an array
instead of a simple string.
 This array contains the values that were selected by the user.
Advanced form handling
• Multivalued Parameters in checkbox element
Advanced form handling
• Working with radio buttons
PHP Session
• A session is a way to store information (in variables) to be used across
multiple pages.
 session_start() : starts a session
o The session_start() function first checks for an existing session ID.
o If it finds one, i.e. if the session is already started, it sets up the session variables and
if doesn't, it starts a new session by creating a new session ID.
• Session variables are set as key-value pairs with the global variable:
$_SESSION
 The stored data can be accessed during lifetime of a session

$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker";

 session_unset() : to remove session data, simply unset the corresponding key


of the $_SESSION
 session_destroy() : destroy the session
Session Demo
SessionExample1.php

SessionExample2.php
Another Session Demo
E-mail With PHP
• Server side scripting language must provide a way of sending e-mail
from the server and, in particular, to take form input and output it to an
e-mail address
• mail($to,$subject,$body[,$headers]); - for sending mail

$to = “abc@gmail.com";
$subject = "Hi There!";
$body = "PHP is one of the best scripting languages around";
$headers = "From: xyz@gmail.com\n";
mail($to,$subject,$body,$headers);
Cookies
• setcookie(cookie-name,cookie-value): instructs the browser to save a
cookie
 setcookie(name, value, expire, path, domain, secure);
 setcookie() goes via response header, which means that it has to be called
before any output is made to the browser (including text, HTML etc)
o The value you set can't be read until next time the page is loaded, ie you can't save a
cookie and read the value in the same page execution
 Eg : setcookie("user_name", "John Doe"); //cookie expires when session ends
 Eg : setcookie("age", "36", time()+3600); //cookie expires after 1 hour
• The value can be retrieved again by using the $_COOKIE superglobal
 Eg : echo $_COOKIE["user_name"];
• To delete a cookie, use the setcookie() function with an expiration date in
the past
 Eg : setcookie("user", "", time() - 3600); //set expiration date to one hour ago
Cookie Demo

cookieSetExample.php

cookieGetExample.php
File handling (read)
• File handling is an important part of any web application. You often need to
open and process a file for different tasks.
 PHP has several functions for creating, reading, uploading, and editing files
 readfile(filename): reads a file and writes it to the output buffer
o is useful if all you want to do is open up a file and read its contents
 fopen(filename,mode) : similar to readfile(), but gives more options
o If an attempt to open a file fails then fopen returns a value of false otherwise it returns
a file pointer which is used for further reading or writing to that file.

Mode What it does


r Opens the file for reading only.
r+ Opens the file for reading and writing.
Opens the file for writing only and clears the contents of file. If files does not exist then it
w
attempts to create a file.
Opens the file for reading and writing and clears the contents of file. If files does not exist then it
w+
attempts to create a file.

Append. Opens the file for writing only. Preserves file content by writing to the end of the file. If
a
files does not exist then it attempts to create a file.
Read/Append. Opens the file for reading and writing. Preserves file content by writing to the end
a+
of the file. If files does not exist then it attempts to create a file.
File handling (read)
 filesize(filename) : returns file length in bytes
 fread(filepointer, length of file) : read a file that is opened with fopen()
 fclose(filepointer) : close the file

<?php echo readfile("sample.txt"); ?>

<?php
$filename = "sample.txt";
$fileptr = fopen( $filename, "r" );
if( $fileptr == false ) {
echo ( "Error in opening file" ); exit();
}
$filesize = filesize( $filename );
$filetext = fread( $fileptr, $filesize );
fclose( $fileptr );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
File handling (read)
• file_get_contents() : reads file contents into a string
$dataStr = file_get_contents($filename);
echo $dataStr;

• file() - Reads entire file into an array $filename = "sample.txt";


with each line of the file corresponding to $dataArr = file($filename);
an element of the array print_r($dataArr);

• fgets(filename) : used to read a single line from a file


File handling
• file_exists(filename) : checks existence of file
• feof() : checks if the "end-of-file" (EOF) has been reached

• fwrite(filepointer, text to be written,[data length]) : A new file can be


written or text can be appended to an existing file
File handling
• copy() : creates a copy of a file

• unlink() : delete a file


File handling : CSV (Comma Separated Values) files

emp.csv

Output – reads
a single line

readCSV.php

Array ( [0] => 1001 [1] => Harry [2] => Accts )
Array ( [0] => 1002 [1] => Jerry [2] => Sales )
while(! feof($file)) {
Array ( [0] => 1003 [1] => Tom [2] => Mktg )
print_r(fgetcsv($file));
} Reads all lines
Output
from csv file
File handling : CSV (Comma Separated Values) files
• update or write to a CSV file using the function fputcsv()
Using the die() function
<?php Warning: fopen(welcome.txt) [function.fopen]: failed to
$file=fopen("welcome.txt","r"); open stream:
?> //if file does not exist? --- No such file or directory in C:\webfolder\test.php on
line 2

<?php
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
?>
Databases
Steps to perform DB operations
• Step-1: Open a Connection using MySQLi procedural
 mysqli_connect(host,[username][,password][,dbname])
 Upon success it returns an identifier to the server; otherwise, FALSE

The connection will be


closed automatically
when the script ends. To
close the connection
before, use the
mysqli_close($conn);
Steps to perform DB operations
• Step 2 : Create a database
 mysqli_query(connection,query) : Perform queries against the database
Steps to perform DB operations
• Step-3 : Create a Table
Steps to perform DB operations
• Step-4a : Insert single record into table

db4-getConn.php

db5-InsertRow.php
Steps to perform DB operations
• Step-4b : Insert multiple records into table
 mysqli_multi_query(connection,query) : Perform multiple queries against the
database
Steps to perform DB operations
Steps to perform DB operations
• Step-5 : Fetching result
• Other ways of fetching result:
 mysqli_fetch_all(result,resulttype) : fetches all result rows and returns the
result-set as an associative array, a numeric array, or both.

 mysqli_fetch_row() : fetches one row from a result-set and returns it as an


enumerated array
Steps to perform DB operations
• Step-6 : Update/Delete rows
PHP & XML
Parsing XML With SimpleXML
• PHP 5's new SimpleXML module simplifies parsing an XML document
 SimpleXML is a tree-based parser.
 Turns an XML doc into an object that provides structured access to the
XML.
Loading XML file
Reading XML using the DOM library
• Built-in DOM parser makes it possible to process XML documents in PHP.
 How to do? Initialize the XML parser, load the xml, and output it
BOOTSTRAP
Getting Bootstrap Ready
• There are two ways to start using Bootstrap on your own web site.
 Download Bootstrap from the oficial website http://getbootstrap.com/ and include
it in your HTML file with little or no customization.
 Include Bootstrap from a CDN
o The http://getbootstrap.com/getting-started/ page gives CDN links for CSS and js files
 A Basic template can be created using the bootstrap files and jquery libraries
Bootstrap Container
• Container is used to wrap the site contents and contain its grid
system
 Thus dealing with the responsive behaviors of your layout.
 There are two container classes in Bootstrap:
o Fixed Container : A fixed container is a (responsive) fixed width container.
o Fluid Container : A fluid container spans the full width of the viewport.
 Note: A container cannot be placed inside a container

<body>
<div class="container">
<h1>Container</h1>
<p>container content</p>
</div>
</body>
Bootstrap Grid System
• Bootstrap grid system allows to properly house the website's content.
 Grid system divides the screen into columns―up to 12 in each row.
 The column widths vary according to the size of screen they're displayed in.
 Hence, Bootstrap's grid system is responsive, as the columns resize
themselves dynamically when the size of browser window changes.
Page Components
• Page components form the basic structure of a web page.
 Examples include page headers, standout panels for displaying important info,
nested comments sections, image thumbnails, and stacked lists of links
• Page Headers :
 Eliminates efforts to neatly display a title with cleared browser default styles,
the proper amount of spacing around it, and a small subtitle beside it

 To add a subtitle beside the title of the page, you can put it inside the same
<h1> tag that we used before; wrap the subtitle inside a <small></small> tag
Page Components : Panels
• Panels are used to display text/images within a box with rounded corners.
 The panel div is divided into three parts: the panel-head, panel-body, and panel-
footer. Each of these panel parts is optional.

• panel-primary for dark blue


• panel-success for green
 Panels come with various color options • panel-info for sky blue
• panel-warning for yellow
• panel-danger for red
Page Components : Thumbnails
• You can add some excerpts to each thumbnail and a Read More button for
linking to different pages in your website.
 Use <div> instead of <a>.
 Then add an excerpt using <p> inside the “caption” div and a link with a “Read
More” anchor and classes btn and btn-primary inside the same “caption” div.
Page Components : List Group
• List group is used for creating lists, such as a list of useful resources or a list
of recent activities.
 You can also use it for a complex list of large amounts of textual content.
 Add the class list-group to a ul element or a div element to make its children
appear as a list.
 The children can be li or a element, depending on your parent element choice.
 The child should always have the class list-group-item.
Page Components : List Group
• We can display a number (eg to indicate pending notifications) beside each
list item using the badge component.
 Add this inside each “list-group-item” to display a number
beside each one : <span class="badge">14</span>
 The badges align themselves to the right of each list item

 We can also apply various colors to each list item by adding list-group-item-*
classes along with list-group-item.
Navigation Components : Navs
• Navs are a group of links that are placed inline with each other for navigation
 There are options to make this group of links appear either as tabs or small
buttons, the latter known as pills in Bootstrap.
 To create tab-like navigation links:

 Vertically stack these pills by attaching an


additional class nav-stacked to it
Navigation Components : Navbar
• navbar gives you the power to generate portions of self-contained bars, which
could be used as whole-application headers, versatile secondary menus for
page content, or as a shell of various navigation-related elements.
 First build a div element, with two classes navbar and navbar-default.

<div class="navbar navbar-default">


</div>

 Next, we'll use a div with class container-fluid inside this navbar element.

<div class="navbar navbar-default">


<div class="container-fluid">
</div>
</div>
Navigation Components : Breadcrumbs
• Breadcrumbs are used to enhance the accessibility of your websites
by indicating the location using a navigational hierarchy, especially in
websites with a significant number of web pages.

You can use <ul> instead of <ol>


Standing Out : labels
• Labels are used to display short text beside other components, such as
important messages and notes.
 To display a label, you need to add a label class to inline HTML elements
such as span and i.

<h3>Jump Start Bootstrap <span class="label label-default">New</span></h3>

 class label-default is necessary to tell Bootstrap which variant of label we


want to use. The available label variants are:
o label-default for gray
o label-primary for dark blue
o label-success for green
o label-info for light blue
o label-warning for orange
o label-danger for red
Standing Out : Buttons
• Its easy to convert an a, button, or input element into a fancy bold
button in Bootstrap; just have to add the btn class
<a href="#" class="btn btn-primary">Click Here</a>

 Buttons come in various color options:


o btn-default for white  And in various sizes:
o btn-primary for dark blue o btn-lg for large buttons
o btn-success for green o btn-sm for small buttons
o btn-info for light blue o btn-xs for extra small button
o btn-warning for orange
o btn-danger for red
Standing Out : Glyphicons
• Glyphicons are used to display small icons.
 They are lightweight font icons and not images.
 There are around 260 glyphicons available for
buttons, navbars , lists and other components
o Eg : To display a heart icon

<span class="glyphicon glyphicon-heart">


</span>
Forms
• Bootstrap greatly simplifies the process of styling and alignment of form
controls like labels, input fields, selectboxes, textareas, buttons, etc.
through predefined set of classes.
 Bootstrap provides three different types of form layouts:
o Vertical Form (default form layout)
o Horizontal Form
o Inline Form
 Standard rules for all three form layouts:
o Wrap labels & form controls in
<div class="form-group">
o Add class .form-control to all <input>, <textarea>,
and <select> elements
• Construct a form with form element
with the form class added to it
Vertical form
Forms : Horizontal Forms
• In horizontal form layout labels are right aligned and floated to left to make them
appear on the same line as form controls.
 Following markup changes required :
o Add the class .form-horizontal to the <form> element.
o Add the class .control-label to the <label> element.
o Use Bootstrap's predefined grid classes to align labels and form controls.
Forms : Inline Form
• In an inline form, all of the elements are inline, left-aligned, and the labels
are alongside.
 Note: This only applies to forms within viewports that are at least 768px wide!
 Add class .form-inline to the <form> element
Bootstrap Typography
• HTML uses default font and style to create headings, paragraphs, lists and
other inline elements.
 Bootstrap overrides default and provides consistent styling across browsers for
common typographic elements.
 Eg, Bootstrap provides its own style for all six standard heading levels
Tables
• Bootstrap provides an efficient layout to build elegant tables
 A basic Bootstrap table has a light padding and only horizontal dividers.
 The .table class adds basic styling to a table

 The .table-striped class adds zebra-stripes to a table


 The .table-bordered class adds borders on all sides of the table and cells
 The .table-condensed class makes a table more compact by cutting cell
padding in half
Jumbotron
• A jumbotron indicates a big box for calling extra attention to some
special content or information.
 A jumbotron is displayed as a grey box with rounded corners. It also
enlarges the font sizes of the text inside it.
 Tip: Inside a jumbotron you can put nearly any valid HTML, including other
Bootstrap elements/classes.
 Use a <div> element with class .jumbotron to create a jumbotron

<div class="jumbotron">
<h1>Bootstrap Tutorial</h1>
<p>Bootstrap is the most popular HTML, CSS, and JS framework for
developing responsive, mobile-first projects on the web.</p>
</div>
images
• To add images on the webpage use element <img> , it has three
classes to apply simple styles to images.
 .img-rounded : To add rounded corners around the edges of the image,
radius of the border is 6px.
 .img-circle : To create a circle of radius is 500px
 .img-thumbnail : To add some padding with grey border , making the image
look like a polaroid photo.

<img src="taj.jpg" class="img-rounded"> <!-- rounded edges-->


<img src="taj.jpg." class="img-circle"> <!-- circle -->
<img src="taj.jpg" class="img-thumbnail"> <!-- thumbnail -->
Alerts
• Bootstrap comes with a very useful component for displaying alert
messages in various sections of our website
 You can use them for displaying a success message, a warning message, a
failure message, or an information message.
 These messages can be annoying to visitors, hence they should have dismiss
functionality added to give visitors the ability to hide them.
<div class="alert alert-success">
Amount has been transferred successfully.
</div>

<div class="alert alert-success alert-dismissable">


<button type="button" class="close" data-dismiss="alert">&times;</button>
Amount has been transferred successfully.
</div>

You might also like