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

PHP Material

Uploaded by

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

PHP Material

Uploaded by

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

AJAX &JSON

April 10, 2019 -1-


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.

April 10, 2019 -2-


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

April 10, 2019 -3-


Dem
o

April 10, 2019 -4-


What isAjax
?
• “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
o No clicking required. Call can be triggered on any event
o Mouse movement is a sufficient event trigger
▪ "Partial screen update" replaces the "click, wait, and refresh" user interaction model
o Only user interface elements that contain new information are updated (fastresponse)
▪ The rest of the user interface remains displayed as it is without interruption (no loss
of operational context)

April 10, 2019 -5-


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

April 10, 2019 -6-


CreatinganAJAX
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
};

April 10, 2019 -7-


Ajax
Demo

April 10, 2019 -8-


AJAX Demo with
XML

April 10, 2019 -9-


AJAX Demo with
JSON

April 10, 2019 - 10 -


PHP (PHP:HYPERTEXT
PREPROCESSOR)

April 10, 2019 - 11 -


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 and the result is returned to the browser as
plain HTML
▪ PHP is free to download and use.
▪ PHP files can contain text, HTML, CSS, JavaScript, and PHP code ; have extension
".php“
• Installing PHP

April 10, 2019 - 12 -


Basic PHPSyntax
• 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> A PHP file normally contains HTML tags, and somePHP
<html> scripting code.
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

// a single-line comment
• Comments in PHP : # also a single-line comment
/*
▪ PHP supports several ways a multiple-lines comment block
spanning multiple lines
*/

April 10, 2019 - 13 -


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!"; echo "I love $txt!"; <?php
$x = 5; echo "I love " . $txt . "!"; $x = 5;
$y = 10.5; $y = 4;
echo $x + $y;
• + is pure math operator: ?>

$x = "15" + 27;
echo($x); //gives 42!!

• 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.

April 10, 2019 - 14 -


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
?>

April 10, 2019 - 15 -


Variables
Scope
• The global Keyword

• The static Keyword


▪ If we want a local variable NOT to be deleted when a function is completed/executed

<?php
function myTest() { Note: The variable is still local to the
static $x = 0; function.
echo $x; $x++;
} Outputs : 0 1 2
myTest();
myTest();
myTest(); ?>
April 10, 2019 - 16 -
Outputdata 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);

April 10, 2019 - 17 -


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)
$handle = fopen("note.txt", "r");
var_dump($handle); Example:
$s1 = "";
$v1 = null;
$bool = false;
• gettype(): Get the type of a variable $no1 = 1;
echo ('$s1 : ' . gettype($s1) . "<br>");
echo ('$v1 : ' . gettype($v1) . "<br>");
echo ('$bool : ' . gettype($bool) . "<br>");
echo ('$no1 : ' . gettype($no1) . "<br>");

April 10, 2019 - 18 -


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

April 10, 2019 - 19 -


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

• String Operators • Comparison Operators


Operator Meaning
Operator Example Result == is equal to
. $txt1 . $txt2 Concatenation of $txt1 & $txt2 != is not equal to
> is greater than
.= $txt1 .= $txt2 Appends $txt2 to $txt1 >= is greater than or equal to
< is less than
<= is less than or equal to

April 10, 2019 - 20 -


Conditional Statements :
syntax

Conditional Statements :example

April 10, 2019 - 21 -


Loops :
syntax

Note : foreach() works only on arrays,


and is used to loop through each
key/value pair in an array

April 10, 2019 - 22 -


User Defined
Functions

April 10, 2019 - 23 -


Function
s
• Passing Parameters by Reference
function square(&$value) {
$value = $value * $value;
}
$a = 3;
square($a);
echo $a;

• Default Parameters
function getPreferences($whichPreference = 'all') {
//code that uses the parameter
}

• 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);
April 10, 2019 - 24 -
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");

April 10, 2019 - 25 -


Indexed
Arrays

April 10, 2019 - 26 -


Associative
Arrays

April 10, 2019 - 27 -


Multidimensional Name Stock Sold
array
• A multidimensional array is an array containing one
Volvo 22 18
BMW 15 13
or more arrays
Saab 5 2
▪ Can be two, three, four, five, or more levels deep.
Land Rover 17 15
$cars = array( Table for this
array("Volvo",22,18), 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


April 10, 2019 - 28 -
Sorting

Arrays
array sort functions and other 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

▪ 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
April 10, 2019 - 29 - parts of an array. array_slice(array,start,length)
String
Functions

April 10, 2019 - 30 -


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


April 10, 2019 - 31 -
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)

April 10, 2019 - 32 -


Global Variables -
Superglobals

April 10, 2019 - 33 -


$_SERVER
Superglobal
▪ Holds information about headers, paths, and script locations
▪ Some of the most important elements that can go inside $_SERVER:

April 10, 2019 - 34 -


$_SERVER
Dem
o
<?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'];
?>

April 10, 2019 - 35 -


$_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']; ?>
</body>
test_get.php

April 10, 2019 - 36 -


Form Handling
($_POST)

April 10, 2019 - 37 -


$_REQUEST
• Used to collect data after submitting an HTML form

April 10, 2019 - 38 -


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

April 10, 2019 - 39 -


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.

April 10, 2019 - 40 -


April 10, 2019 - 41 -
Advanced form
handling
• Multivalued Parameters in checkbox element

April 10, 2019 - 42 -


Advanced form
handling
• Working with radio buttons

April 10, 2019 - 43 -


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 sessionID.
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

April 10, 2019 - 44 -


Session
Demo
SessionExample1.php

SessionExample2.php

April 10, 2019 - 45 -


Another Session
Demo

April 10, 2019 - 46 -


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 = “[email protected]";
$subject = "Hi There!";
$body = "PHP is one of the best scripting languages around";
$headers = "From: [email protected]\n";
mail($to,$subject,$body,$headers);

April 10, 2019 - 47 -


Cookie
s
• 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

April 10, 2019 - 48 -


Cookie
Demo

cookieSetExample.php

cookieGetExample.php

April 10, 2019 - 49 -


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.
April 10, 2019 - 50 -
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>" );
?>

April 10, 2019 - 51 -


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 with each line of the file corresponding
to an element of the array
$filename = "sample.txt";
$dataArr = file($filename);
print_r($dataArr);

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

April 10, 2019 - 52 -


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

April 10, 2019 - 53 -


File
handling
• copy() : creates a copy of a file

• unlink() : delete a file

April 10, 2019 - 54 -


File handling : CSV (Comma SeparatedValues)
files

emp.csv

Output – reads a
single line

readCSV.php

Array ( [0] => 1001 [1] => Harry [2] =>Accts )


Array ( [0] => 1002 [1] => Jerry [2] => Sales ) Array (
while(! feof($file)) { [0] => 1003 [1] => Tom [2] => Mktg )
print_r(fgetcsv($file));
}
Reads all lines
Output
from csv file
April 10, 2019 - 55 -
File handling : CSV (Comma SeparatedValues)
files
• update or write to a CSV file using the function fputcsv()

April 10, 2019 - 56 -


Using the die()
function
<?php Warning: fopen(welcome.txt) [function.fopen]: failed to open
$file=fopen("welcome.txt","r"); 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");
}
?>

April 10, 2019 - 57 -


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);

April 10, 2019 - 58 -


Steps to performDB
operations
• Step 2 : Create a database
▪ mysqli_query(connection,query) : Perform queries against the database

April 10, 2019 - 59 -


Steps to performDB
operations
• Step-3 : Create a Table

April 10, 2019 - 60 -


Steps to perform DB operations
• Step-4a : Insert single record into table

db4-getConn.php

db5-InsertRow.php

April 10, 2019 - 61 -


Steps to performDB
operations
• Step-4b : Insert multiple records into table
▪ mysqli_multi_query(connection,query) : Perform multiple queries against the database

April 10, 2019 - 62 -


Steps to performDB
operations

April 10, 2019 - 63 -


Steps to performDB
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

April 10, 2019 - 64 -


Steps to performDB
operations
• Step-6 : Update/Delete rows

April 10, 2019 - 65 -


PHP &XML

April 10, 2019 - 66 -


ParsingXMLWith
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.

April 10, 2019 - 67 -


Loading XML
file

April 10, 2019 - 68 -


Reading XMLusing 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

April 10, 2019 - 69 -


BOOTSTRAP

April 10, 2019 - 70 -


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

April 10, 2019 - 71 -


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 : Afixed 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>

April 10, 2019 - 72 -


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.

April 10, 2019 - 73 -


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

April 10, 2019 - 74 -


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.

▪ Panels come with various color options • panel-primary for dark blue
• panel-success for green
• panel-info for sky blue
• panel-warning for yellow
• panel-danger for red
April 10, 2019 - 75 -
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.

April 10, 2019 - 76 -


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.

April 10, 2019 - 77 -


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.

April 10, 2019 - 78 -


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

April 10, 2019 - 79 -


April 10, 2019 - 80 -
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>

April 10, 2019 - 81 -


April 10, 2019 - 82 -
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>

April 10, 2019 - 83 -


StandingOut :
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

April 10, 2019 - 84 -


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
o btn-primary for dark blue ▪ And in various sizes:
o btn-success for green o btn-lg for large buttons
o btn-info for light blue o btn-sm for small buttons
o btn-warning for orange o btn-xs for extra small button
o btn-danger for red

April 10, 2019 - 85 -


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 . Eg : To display a heart icon

<span class="glyphicon glyphicon-heart">


</span>

April 10, 2019 - 86 -


Form
s
• 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

April 10, 2019 - 87 -


Verticalform

April 10, 2019 - 88 -


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.

April 10, 2019 - 89 -


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

April 10, 2019 - 90 -


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

April 10, 2019 - 91 -


Table
s
• 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

April 10, 2019 - 92 -


Jumbotr
on
• 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>

April 10, 2019 - 93 -


image
s
• 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 -->

April 10, 2019 - 94 -


Alert
• sBootstrap 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>

April 10, 2019 - 95 -

You might also like