0% found this document useful (0 votes)
536 views99 pages

Web Designing: HTML, PHP, Mysql, Javascript

The document provides an overview of a web design course covering HTML, PHP, MySQL, and JavaScript. It includes the following key points: 1) The course covers basics of the internet, HTML tags and syntax, server-side scripting with PHP, introduction to databases with MySQL, and integration of PHP and MySQL. 2) HTML topics include basic tags, attributes, links, images, tables, lists, and frames. PHP is introduced for server-side scripting and dynamic websites. 3) MySQL is covered for database operations like create, insert, delete, select, update, and joins. The document emphasizes using PHP with MySQL for client-server interactions on websites.

Uploaded by

Being Amar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
536 views99 pages

Web Designing: HTML, PHP, Mysql, Javascript

The document provides an overview of a web design course covering HTML, PHP, MySQL, and JavaScript. It includes the following key points: 1) The course covers basics of the internet, HTML tags and syntax, server-side scripting with PHP, introduction to databases with MySQL, and integration of PHP and MySQL. 2) HTML topics include basic tags, attributes, links, images, tables, lists, and frames. PHP is introduced for server-side scripting and dynamic websites. 3) MySQL is covered for database operations like create, insert, delete, select, update, and joins. The document emphasizes using PHP with MySQL for client-server interactions on websites.

Uploaded by

Being Amar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Web Designing

HTML, PHP, MySQL, JavaScript

Course Content

Basics of Internet

www Basic Tags Limitations Client Server Protocol Installation of XAMPPLITE(For PHP and MYSQL) Variables, Functions File I/O Example : Page Counter

HTML

Server Side Scripting - PHP


Contd...

More PHP Examples

Sessions Cookies Operations


Introduction to Database MySQL

Create Insert Delete Select Update Join and Aggregate Operations

Contd

Primary and Foreign Key Integration of PHP with MYSQL

www
Major Growth after Development of HTML
HyperText Markup Language What are Browsers
Programs that can read HTML Documents and display those documents in defined form Example Internet Explorer, Mozilla Firefox, Opera, Google Chrome etc. Different looks of same HTML page in different browsers

What happens exactly when you open a HTML file through a browser
On your system A website

HTML works : HTTP Protocol


1
SERVER 2

This is like Client speaking with the server. 1. Requesting a webpage 2. HTML files live on a Web server. The Web server is hooked into the Internet and when people type in the URL of a page, they are actually calling the file from that Web server. When someone requests an HTML page, the Web server sends html data to the client. The client's browser turns the long string of text(html data) into a viewable page.

HTML
HTML documents/page(In one sense : code)
describe web pages contain HTML tags and plain text are also called web pages

A Simple MarkUp language


Made up of tags Ex: head , body, p , div , img etc Syntax
Simplest : <tag> Content </tag> Advanced : <tag tagattributes> Content </tag>

Every tag except line break(<br>) should have an end tag associated with it The browsers do not display the HTML tags, but use the tags to interpret the content of the page

Syntax
<html> <head> </head> <body> </body> </html> The text between <html> and </html> describes the web page The text between <body> and </body> is the visible page content

Basic Tags
Paragraph Tag
<p>

Heading Tag
Example : <h1>

First Example : web1.htm


Can also save as web1.html

Tag Attributes
For Additional Information
Example
<p id=para1 style=font-size=40px;color=red;> Paragraph1 </p> id gives a specific id/name to a tag by which it can be recognised More examples : src attribute for <img> and href attribute for <a>

web2.htm
Note the Nested Tags (Tags are always Nested)

Link Tag and Images


Hyperlink
Address/Reference to another resource/webpage <a> tag Examples
<a href=http://www.iitk.ac.in/>IITK Home</a> <a href=web4.htm>Web 4</a>

Image
<img src=url> </img> Additional Info like width, height,alt(for alternate text to be displayed if image fails to load for some reason) etc

Tables

<table tableAttributes> <tr trAttributes> for starting a row <td tdAttributes> for a data cell Example
<table border="1"> <tr> <td>r1, c1</td> <td>r1, c2</td> </tr> <tr> <td>r2, c1</td><td>r2, c2</td> </tr> </table>

Lists
Unordered List
<ul>

Ordered List
<ol>

Definition List
<dl>

List Items
<li>

Example
web4.htm

Frames
Can display more than one HTML document in the
same browser window.
Each HTML document is called a frame, and each frame is independent of the others.(Frame handling depends on the browsers.

Example
<frameset cols="25%,75%"> <frame src="frame_a.htm"> <frame src="frame_b.htm"> </frameset> noresize attribute, navigation frame, inline frame, anchor etc target attribute _blank , another frame etc

web5.htm

Forms
Form elements (web6.htm)
Elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form.

<form> tag.
Examples of form elements input tag radio buttons checkboxes submit button and action submit button and action ! Will cover in more details. This now serves as a simple motivation for client-server interaction and hence the introduction of php

Added Note
Many softwares available which fasten the work
Simple to use Microsoft FrontPage Adobe Dreamweaver Web Studio etc etc

Server Side Scripting


Motivation Server Side Scripting Languages
PHP ASP

PHP
Executed on server Need PHP installed Supports many databases
Like MySQL, Oracle, ODBC etc

For programming dynamic websites

Installing PHP
XAMPPLite
For PHP Server and MYSQL Easiest of all installations

PHP
PHP stands for PHP: Hypertext Preprocessor
PHP files can contain text, HTML tags and PHP scripts PHP files(i.e output) are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml"

PHP code always inside


<?php
?>

Client-Server Protocol

When client opens a webpage : PHP processes PHP instructions contained in a webpage and sends the output to the Client as HTML

When a Form is Submitted


1

This is like Client speaking with the server. 1. On submission of Form : Data corresponding to form is sent to the server 2. The WebServer uses the Data and sends required output to the Client i.e WebBrowser. The browser interprets the data as HTML data.

How does it work exactly


Before Sending a webpage
WebServer checks files with html or php extensions for php codes (i.e codes included in <?php phpcode ?>). Any php code found in the page are executed The respective codes are replaced by respective outputs before the webpage is sent to the browser

When forms are submitted/link is clicked(php


link)/url is typed in Once a webpage is fully downloaded, php plays no further role. (Exception : With JavaScript and Ajax)

Our 1st PHP Program


Printing Hello World
web1hello.php web2hello.php web3hello.php web4hello.php

Look at all HTML Source Code


Note : Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. Two Basic statements to output text echo : sends output to the browser print

Variables in PHP
Variable always prefixed with $ sign
A variable does not need to be declared before adding a value to it. variable is declared automatically when you use it. PHP automatically converts the variable to the correct data type, depending on its value Example $somenum = 30 ; $mystr = Hello Again ; $mynum = 30 + 20 ; A variable name must start with a letter or an underscore "_ can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )

Variable Types : 8 Primitive Types


Four scalar types: boolean : expresses truth value, TRUE or FALSE. Any non zero values and non empty string are also counted as TRUE. integer : round numbers (-5, 0, 123, 555, ...) float : floating-point number or 'double' (0.92838, 23.0) string : "Hello World", Good Morning, a etc etc Two compound types: array object two special types: resource ( one example is the return value of mysql_connect() function) NULL

echo and concatenation operator


Example
$name = Michael ; $age = 31 ; echo $name . Scofield died at age . $age ; More examples in we5variables.php (gettype and Settype next slide)

Data Types Continued


gettype . Example $pi = 3.14 ; echo gettype($pi) ; Settype Lets you overwrite the datatype of a variable If the stored value is not suitable to be stored in new type, then, modified to the closest value possible $val = 15th August 1947 ; Settype($val , integer) ; echo $val ; Final value of $val = 15 Conversion converts everything till the 1st nonnumeric character to integer

Type Juggling
Sometime PHP performs implicit data type
conversion if values are expected to be of a particular type. Example
echo 100 + 10 inches ; Output = 110 ; echo 100 . 10 inches ; Output = 10010 inches $num = 100 . 10 ; echo $num ; Output = 10010 More Examples in web5variables.php

PHP operators
Arithmetic
+ , - , * , / , % , ++ , --

Assignment
=, +=, -=, *=, /= , .=, %=

Comparision
==, !=,===,!== >, <, >=, <=

Logical
!, &&, || , and, xor, or (in precedence order)

web6operators.php

Flow Control
web7flowcontrol.php Conditional Statements
if (condition) {code to be executed} if(condition) {code1 to be executed} else{code2 to be executed} If(condition) {code1 to be executed} elseif(condition){code2 to be executed} elseif(condition){code3 to be executed} elseif(condition}{coden to be executed} else{code to be executed}

Flow Control Cont..


Conditional Statements continued
switch (n) { case case1: code to be executed if n=case1; break; case case2: code to be executed if n=case2; break; default: code to be executed if n is different from above cases; }

Flow Control Cont


Loops
while (condition) { code to be executed; } do { code to be executed; } while (condition); for (initialize; condition; increment) { code to be executed; } Will come to foreach later(since it concerns arrays)

Flow Control Cont


For
initialize: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop)

Breaking out of a loop


break : Tells PHP to immediately exit the loop and continue the rest of the script. continue : Tells PHP to end the current pass of loop, but the script will jump back to the top of the same loop and continue execution until the loop condition fails.

Arrays
Stores a set of values. Example Suppose you have to store a sequence of n numbers such that T(n) = 2*n + 3 If it werent for arrays you would do the following : $T_0 = 2 * 0 + 3 $T_1 = 2 * 1 + 3 $T_n = 2 * n + 3 Using arrays for($i=0;$i<=n;$i++) { $T[$i] = 2 * ($i) + 3 ; } Similarly for obtaining the sum of the sequence $sum = 0 ; for($i=0;$i<=n;$i++) {$sum = $sum + $T[$i] ;}

Creating and Accessing Arrays


Numeric Arrays : Indices are numeric
Creating Method 1 $Instructor=array(Akhtar",Afro",Babu",Chini"); Method 2 $Instructor[0] = Akhtar ; $Instructor[1] = Afro ; $Instructor[2] = Babu ; $Instructor[] = Chini ; //Same as $Instructor[3] =Chini; Note : //if you omit an index number, next index number is automaticaly used. Accessing : Example, accessing the 6th element $var = $Instructor[5] ;

Creating and Accessing Arrays


Associative arrays
each ID key is associated with a value Creating
Method 1 $section = array("Akhtar"=>3, "Afro"=>1, "Babu"=>2); Method 2 $section["Akhtar"] = 3 ; $section["Afro"] = 1 ; $section["Babu"] = 2 ; echo "Afro is the instructor of Section " . $section["Afro"] ; // Note : Values are stored in the order in which they are defined

Multi-Dimensional Arrays
2 Dimensional
Array of Arrays

Similarly any other Multi-Dimensional Array Useful for working with matrices etc web8arrays.php with examples of working with
multi-dimensional arrays

print_r
Prints the complete contents of an array
print_r($arrayname)
Prints the contents without formatting

echo <PRE> ; print_r($arrayname) ; echo <PRE> ;


Prints the contents after formatting

Example in web8arrays.php

foreach
foreach ($array as $value) { code to be executed; } foreach($array as $key => $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value . $key is the respective key index Examples in web8arrays.php

Functions
A function performs a specific task.
Syntax to define a function function functionName(Parameters) { code to be executed; } Syntax to call a function In case there is a return type, same type as $var $var = functionName(Parameter Values) ; In case there is no return type, functionName(Parameter Values) ;
o o

Note : A function is not executed unless called. web9functions.php

Advantages of functions
Less typing, need not write the same piece of code
many times. Easy to maintain. Example
Suppose
function add_tax($amount){ return $amount * 1.07 ;} echo add_tax(100) ; echo add_tax(199) ; //etc etc several such statements for different values of $amount If the rate changes, for example to 9%, then the only change we need to make is return $amount * 1.09 ; Need not make any more changes

Functions and PHP In-Built Functions


Examples of defining own functions Examples of PHP In-Built functions
Built-In Functions: Provided by PHP
Arithmetic Functions String Functions Array Functions Date and Time Functions etc etc

File I/O
File Input / Output is corresponding to files on the
webserver. Function for opening a file : fopen(filename, permissions) Example
$filepointer = fopen(filename.txt, r+); The variable $filepointer doesnot contain the contents of the file. It only points to a specified file. fgets($filepointer) ->To read a file line by line fwrite($filepointer,$ContentToWrite) ->To write to a file fclose($filepointer) -> To close a file

File I/O : Permissions


r
Read only. Starts at the beginning of the file

r+
Read/Write. Starts at the beginning of the file

w
Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist

w+
Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist

a
Append. Opens and writes to the end of the file or creates a new file if it doesn't exist

File I/O Permissions


a+
Read/Append. Preserves file content by writing to the end of the file

x
Write only. Creates a new file. Returns FALSE and an error if file already exists

x+
Read/Write. Creates a new file. Returns FALSE and an error if file already exists

feof($filepointer)
Tells you if you have reached the end of a file

Example
web10file.php, web11counter.php

More To Come
Forms Revisited
$_GET $_POST

Sessions
$_SESSION

Cookies Executing programs on Server


passthru, backticks,exec,

But before that, we try to understand Databases


through MYSQL

MYSQL
MySQL is a database. The data in MySQL is stored in database objects
called tables. A table is a collections of related data entries and it consists of columns and rows. Queries
A query is a question or a request. With MySQL, we can query a database for specific information and have an answer set returned.

SQL is a fairly large topic. But we will deal with


only the practical basics.

Client-Server-DB Protocol
1

Client-Server DB Protocol
Continued
1. Client makes a webpage request/ on submission of a form 2. Exchange of data between PHP Server and the Database 3. Output after processing the database data

To view your database (if you are using xampp)


localhost/phpmyadmin or ipaddress/phpmyadmin Default username = root and password is null i.e nothing Can change your database username password

mysql_connect and mysql_close


First step in PHP-SQL interaction Connection with the SQL Server Syntax
mysql_connect(servername,username,password)

Example
$con=mysql_connect(localhost:3306,root,) ; $con=mysql_connect(172.24.0.224,tcore,G00g!3);

Last step : To close the connection


mysql_close($con) ;

die and mysql_error


die :
Terminates the Program. Used when a connection attempt is unsuccessful etc etc.

mysql_error :
Displays the error if any

Example
$con = mysql_connect("localhost",jacob",JloCke"); if (!$con) { die(Could not connect: . mysql_error( )); }

Queries
Any QUERY is executed by the following
command.
mysql_query($query,$con);
$query is a variable containing a query $con is the connection specifier

Example of queries
CREATE SELECT DELETE etc etc

CREATE
Creating a Database
CREATE DATABASE databasename Example
mysql_query("CREATE DATABASE employerinfo",$con)

Creating a Table in a Database


CREATE TABLE nameoftable ( column_name1 data_type, column_name2 data_type, column_namen data_type )

CREATE Continued
Example
mysql_select_db(employerinfo", $con); $sql = "CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int )"; // Execute query mysql_query($sql,$con);

Note : mysql_select_db is used to select a database

INSERT
INSERT INTO table_name
VALUES (value1, value2,,valuen)
The values are inserted in the default column order

INSERT INTO table_name


(col1, col2, ...,coln) VALUES (value1, value2,..,valuen) Example : Next Slide

INSERT Example
$result = mysql_query("INSERT INTO Persons
(FirstName, LastName, Age) VALUES (Clint', Eastwood', '35')");

$fname = Illeana ; $lname = Joseph ; $age = 21


; $newquery = INSERT INTO Persons (FirstName, LastName, Age) VALUES ($fname', $lname', $age)" $myresult = mysql_query($newquery);

SELECT Without any condition


The SELECT statement is used to select data from
a database.
SELECT colname FROM table_name SELECT colname1, colname2, , colnamek FROM table_name SELECT * FROM table_name
This selects all the columns from the table

SELECT with WHERE


WHERE
The WHERE clause is used to extract only those records that fulfill a specified criterion. SELECT colname1,colname2,,colnamen FROM table_name WHERE colnamei operator value Operator is any comparision operator
=.=>,<=,>,< etc etc

Example
$result = mysql_query("SELECT * FROM Persons WHERE FirstName=Claire"); $result2 = mysql_query("SELECT * FROM Persons WHERE FirstName=Claire AND LastName=CheerLeader");

UPDATE
The UPDATE statement is used to update existing
records in a table.
UPDATE table_name SET column1=value1, column2=value2,...columnn=valn WHERE some_column=some_value mysql_query("UPDATE Persons SET Age = 20' WHERE FirstName = Hiro' AND LastName = Nakamura'");

DELETE
The DELETE FROM statement is used to delete
records from a database table.
DELETE FROM table_name WHERE some_column = some_value If you omit the WHERE clause, all records in table table_name will be deleted! Example
mysql_query("DELETE FROM Persons WHERE FirstName=Genelia'");

ORDER BY
The ORDER BY keyword
is used to sort the data in a recordset. sorts the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword. SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
$result = mysql_query("SELECT * FROM Persons ORDER BY age"); It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are equal:

mysql_fetch_array
The value returned in by mysql_query is of
resource datatype. Example
$result = mysql_query("SELECT * FROM Persons WHERE FirstName=Claire"); $result is of datatype resource

mysql_fetch_array helps in extracting the answer


records one by one in an array with keys/indices as the value of the respective column.
In above example, the keys would be FirstName,LastName, Age , for the table created previously in CREATE Slide

Each call to mysql_fetch_array($result) returns


the next row in the answer recordset.

mysql_fetch_array cont
Example
$result = mysql_query("SELECT * FROM Persons"); while($row = mysql_fetch_array($result)) { echo $row[FirstName] . " " . $row[LastName]; echo "<br />"; } Note : I am not comparing, I am assigning mysql_fetch_array($result) to $row.

Added Note
SQL contains many more things.(Primary key etc) Certain applications will require functions like
COUNT,HAVING, GROUP BY etc etc.
Example
SELECT AVG(AGE) AS AvgAge FROM Persons SELECT * FROM Persons WHERE Age>(SELECT AVG(Age) FROM Persons)

-End of Lecture 1-

FORMS Revisited
<form action=login.php" method="get">
Username: <input type="text" name=uname" /> Password: <input type=password" name=passw" /> <input type="submit /> </form>
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. In above example, the values are available in the following variables $_GET[uname] and $_GET[passw] respectively. Example : web13form.html

$_GET
The built-in $_GET function is used to collect
values from a form sent with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send (max. 100 characters). When the user clicks the "Submit" button, the URL sent to the server could look something like this:
http://localhost/aca/login.php?uname=amar&password=vest ronge

The login.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array):

$_GET
When to use method="get"?
When using method="get" in HTML forms, all variable names and values are displayed in the URL. This method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

$_POST
The built-in $_POST function is used to collect
values from a form sent with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, there is an 8 Mb max size for the POST method, by default (can be changed). When the user clicks the "Submit" button, the URL will look like this
http://localhost/aca/login.php

The login.php" file can now use the $_POST to collect form data (the names of the form fields will automatically be the keys in the $_POST array):

$_POST
When to use method="post"?
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

UPLOADING Files
<form action="upload_file.php" method="post"
enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form>

UPLOADING Files
upload_file.php
if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; }

Uploading Files
$_FILES["file"]["name"] - the name of the uploaded file $_FILES["file"]["type"] - the type of the uploaded file $_FILES["file"]["size"] - the size in bytes of the uploaded file $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server $_FILES["file"]["error"] - the error code resulting from the file upload

Note:
To save the file in a specific folder, you need to use file copy functions to copy from temporary location.

Moving Files
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

isset function and unset


isset($var) returns true if a variable $var has been
set i.e declared/assigned a value and is not NULL. isset($a,$b,)
Evaluation from left to right till it encounters the 1st unset variable. If no such variable is encountered, then returns true.

Major use comes with session variables, cookies


etc unset($var) is used to clear a variable $var i.e destroys the specified variable(s)

PHP Cookies
A cookie is often used to identify a user.
A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Create Cookie
setcookie(name, value, expire, path, domain); The setcookie( ) function must appear BEFORE the <html> tag. The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received

Cookies
Example
<?php setcookie("user", Hugo Reyes", time()+3600); ?> <html> ..... This sets a cookie with a name user to value Hugo Reyes for a time of 1 hour

$_COOKIE
To retrieve a cookie. Some another php script can retrieve the above cookie by using $_COOKIE[user]

Cookies
Delete a cookie
Set expiration time to some time in past Example
setcookie("user", "", time()-3600);

web13form.html

Sessions
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website The above point shows the difference between Cookies and Sessions. But most of the time they are used to achieve the same effect.

Sessions
To Start a Session session_start( );
The session_start( ) function must appear BEFORE the <html> tag.

Storing and retrieving a session variable.


$_SESSION[username] = $p ; $var = $_SESSION[username] ;

To end a Session
Ends automatically when a user closes a particular website. session_destroy( ) Note : All session variables are destroyed.

To unset a particular variable use


unset($_SESSION[uname]) ;

Example
Page counter for a specific session.

JAVASCRIPT : Client Side Scripting


What Can JavaScript do ?
JavaScript gives HTML designers a programming tool JavaScript can put dynamic text into an HTML page
A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page

JavaScript can react to EVENT.


A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element or on using the keyboard etc.

JavaScript can read and write HTML elements.


A JavaScript can read and change the content of an HTML element

Cont ...
JavaScript can be used to validate data
A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser
A JavaScript can be used to detect the visitor's browser, and depending on the browser - load another page specifically designed for that browser

JavaScript can be used to create cookies


A JavaScript can be used to store and retrieve information on the visitor's computer

Syntax
Method 1
<script type="text/javascript"> </script> JavaScript code is inside the above two tags.

Method 2
<script type="text/javascript src=filename.js"> </script> JavaScript code is inside the file filename.js

Hello World
<html><head></head>
<body> <script type="text/javascript"> document.write(<p>Hello World!</p>"); </script> </body></html> Note : document.write( ) function writes html elements to the page. Another example.
document.write(<p>Hello+ x + </p>) ;
x is a variable with some value. (Similar to System.out.print in java

Browsers with JavaScript Disabled


Browsers that do not support JavaScript, will
display JavaScript as page content(i.e plain text) To prevent this :
<script type="text/javascript"> //<!-document.write("Hello World!"); //--> </script> If script is enabled, <!-- means nothing to the Javascript since // at the end comments it out. If script is disabled, // mean nothing in html hence <! and --> is a comment tag

<head> and <body>


Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, go in the head section. If you place a script in the head section, you will ensure that the script is loaded before anyone uses it.

Scripts in <body>
Scripts to be executed when the page loads go in the body section. If you place a script in the body section, it generates the content of a page.

Note : One can place unlimited number of scripts


in an html page

JavaScript Variables
Rules for JavaScript variable names:
Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter or the underscore character Note: JavaScript is CASE SENSITIVE and hence the variables are also case sensitive.

Declaration : Irrespective of datatype


var x ;

Example.
var name ; name = akhtar ; var x ; x = 5 ;

Cont
Note : You can assign values to variables without
declaring them
x=5; Same as : var x ; x = 5 ; Same as var x = 5 ;

Re-declaring a variable
Unlike other languages, you can re-declaring a variable is not an error. However, if no value is assigned in the new declaration, previous value is copied.

Cont
Example :
var x = sid ; var x ; The value of x is still sid

Operators : Same as in other languages Operator +


Like Java, + is used to concatenate strings. + between two integers is arithmetic plus
Ex : var x = 5 + 5 ; //x = 10

+ between an integer and a String is concatenation +


Ex: var x = 5 + 5; //x=55

A few more operators


== , === same is in php
== for comparing values === for comparing values and data-type too.

Conditional operator
variablename=(condition)?value1:value2 Equivalent to
if(condition) {variablename = value1;} else {variablename = value2 ;}

Control Flow statements


if, if else, for, switch, while : same as in Java/C++

Events
Event : Roughly, Something which a user does on
a client machine(browser) Example
onclick, onfocus, onload, onmouseover, onkeyup etc

We specify an event inside an html element with a


function. Example
<input type="button" value="Register" onclick = "UserRegister( )" /> UserRegister( ) is some function defined in head section.

POP-Up Boxes
Alert Box
alert(Hello) ;

Confirm Box
confirm(Hello");

Prompt Box
prompt("sometext","defaultvalue");

Example : web15pop.htm

DOM

document.getElementById
Very Useful function document.getElementById(somename) returns
the element with id = somename Similarly
document.getElementsByName(somename) Returns an array of elements with name = somename Now look at the example web15pop.htm again.

Lifetime of JavaScript Variables


If you declare a variable within a function, the
variable can only be accessed within that function. When you exit the function, the variable is destroyed. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.

Array and for in


var myarr = new Array( );
myarr[0] = alpha ; myarr[1] = beta ; etc etc Or with associative keys var myarr = new Array( ); myarr[jan] = 31 ; myarr[feb] = 20 ; etc etc for in : A little bit similar to foreach of php. Difference : Reads keys one by one
var myarrkeys ; for(myarrkeys in myarr) {document.write(myarr[myarrkeys]) ;}

innerHTML
By using innerHTML one can change the HTML
contents of a page element(tag) Example
document.getElementById(somename).innerHTML = <form method=\"get\" action=\"\><input type=\"text\" id=\"q\" /><input type=\"submit\" value=\"Search\</form> ;

Very Useful to change a complete page element. Usually changes a <div id=somename> </div>
element.

-End of Lecture 2-

You might also like