MyPhp Materials
MyPhp Materials
UNIT I:
VB Script and Java Script: Language structure - control structure - Procedures and
functions - Error handling.
UNIT II:
VB Script: Input & Output - Data Validation -Integration with Forms – Activex Control
& Scripting
UNIT III:
Java Script: Form Validation – SSI and Cookies – Frames and Windows – MIME Types -
Plugins
UNIT IV:
PHP: Server side scripting Language: Basic syntax - Types - Variables - Constants -
Expressions - Operators - Control Structures
UNIT V
PHP : Functions - Classes and Objects - HTML forms - HTTP authentication with PHP -
Cookies - Handling file uploads - Using remote files - Connection handling - Database
Connections.
TEXT BOOKS:
1. Christopher J.Goddard, Mark White, Mastering VB Script‖, Galgotia publications, New Delhi.
2. Lee Purcell, Mary Jane Mara, ―The ABCs of Javascript‖,
3. Steven Holzner, ―PHP: The Complete Reference‖
Index Page (PHP)
Example
Total Number
Total Number
Starting Page
of Programs
Ending Page
Particulars
Programs
of Pages
Units
Starting Ending
No. No.
JavaScript
1 47 47 1 40 40
I
VBScript
48 84 37 41 80 40
VBScript
II
85 101 17 81 91 11
JavaScript
III
General
215 229 15 204 207 4
Topics
Unit-I
JAVA SCRIPT
Java Script was released by Netscape and Sun Micro system in the year 1995, Java script is not similar like java.
CLIENT-SIDE
Client-side JavaScript is the most common form of the language. The script should be included in HTML
document for code to be interpreted by the browser. Web pages need not be a static HTML, it can include
programs interact with the user, control the browser, and dynamically create HTML content. JavaScript
code is executed when the user submits the form, and only if all the entries are valid, they would be
submitted to the Web Server. JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
ADVANTAGES OF JAVASCRIPT
• Less server interaction can validate user input before sending the page off to the server. This saves
server traffic, which means fewer loads on your server.
• Immediate feedback to the visitors they don't have to wait for a page reload to see if they have
forgotten to enter something.
Nandha Arts and Science College PHP – I Unit BCA Department
• Increased interactivity can create interfaces that react when the user however over them with a
mouse or activates them via the keyboard.
• Richer interfaces can use JavaScript to include such items as drag-and-drop components and sliders
to give a Rich Interface to your site visitors.
LIMITS OF JAVASCRIPT- It cannot a full-fledged programming language will lack some features−
Development Tools
The major strengths of JavaScript are not required expensive development tools, will start with a simple text
editor such as Notepad. Since it is an interpreted language inside the context of a web browser, you don't
even need to buy a compiler. To make our life simpler, various editing tools are presently outcome.
Microsoft FrontPage
FrontPage also provides
web developers with a
number of JavaScript tools
to assist in the creation of
interactive websites. It was
branded as part of the MS
Office suite from 1997 to
2003. First released in Dec.
2006. MS FrontPage has
since been replaced by MS
Expression Web &
SharePoint Designer, along MS Office`97.
Features
FrontPage 2003 consists of a Split View option to allow the user to code in Code View and preview in Design
View without the hassle of switching from the Design and Code View tabs for each review. Dynamic Web
Templates (DWT) were included for the first time in FrontPage 2003 allowing users to create a single
template that could be used across multiple pages and even the whole Web site. Interactive Buttons give
users a new easy way to Create Web graphics for navigation and links.
Java Script 2
Nandha Arts and Science College PHP – I Unit BCA Department
Macromedia Dreamweaver MX
Dreamweaver was created by Macromedia in 1997, and was maintained by them until Macromedia
was acquired by Adobe Systems in 2005. Macromedia Dreamweaver MX is an easy, powerful, and
open authoring tool that every
member of the development
team can use to quickly build
robust websites and Internet
applications. Macromedia
Dreamweaver MX is a very
popular HTML and JavaScript
editor in the professional web
development crowd. It provides
several handy prebuilt JavaScript
components, integrates well
with databases, and conforms to
new standards.
Features
Dreamweaver is a web design and
development application that
combines a visual design surface
known as Live View and a code
editor with standard features such
as syntax highlighting, code
completion, and code collapsing. Combined with an array of site management tools, Dreamweaver lets its users
design, code and manage websites as well as mobile content.
Dreamweaver supports syntax highlighting for the following languages
Action Script, Active Server Pages (ASP),C#, Cascading Style Sheets (CSS), ColdFusion, Extensible Hypertext Markup
Language (XHTML), Extensible Markup Language (XML), Extensible Style sheet Language Transformations (XSLT),
Hypertext Markup Language (HTML), JavaScript, PHP, Visual Basic Script Edition (VBScript) and Wireless Markup
Language (WML).
Java Script 3
Nandha Arts and Science College PHP – I Unit BCA Department
Macromedia HomeSite 5
HomeSite was an HTML editor originally developed by Allaire
Corporation. Unlike WYSIWYG (what you see is what you get), HomeSite were designed for direct
editing, or "hand coding," of HTML and JavaScript other website languages. After a successful
partnership with the company to
distribute it alongside its own
competing Dreamweaver
software, HomeSite was acquired
by Macromedia in 2001, after
which elements of the software
were integrated into
Dreamweaver. Following the
acquisition of Macromedia by
Adobe Systems, the company
announced on May 26, 2009 that
HomeSite would be discontinued.
Features
a. Extensively script-able to automate tasks or to perform advanced tasks using JavaScript or VBScript.
b. Macro recorder can record a series of actions to create scripts for later playback
c. Enhanced code snippets save time by creating and saving reusable blocks of code, and can prompt for
variable replacement when used.
d. Customizable syntax color-coding for ASP, CFML, CSS, HTML, Java, JavaScript, JSP, Perl, PHP, SQL,
VBScript, VTML and XHTML. Syntax-coloring parser syntax and examples are available to help users.
e. Search and replace utility
f. CSS editing via the included Top Style Lite, or via integration with the full version of Top Style, if available,
check your code with the built-in Code Validator, or use CSE HTML Validator with UI integration.
g. Integrated help browser shows installed help docs or HTML-format document sets added by the user. Useful for
local, searchable copies of standards, tutorials, language references, etc.
h. Project management and built-in FTP help manage and upload websites
i. Built-in tools for page link-checking, document weight and spell-checking
j. XHTML 1.0 Support
Java Script 4
Nandha Arts and Science College PHP – I Unit BCA Department
Java Script 5
Nandha Arts and Science College PHP – I Unit BCA Department
Java Powered by Sun Micro System, Open JDK, many others Java Script powered by Netscape Navigator
Java programs statement terminated by Semicolon(;) Java Script programs also same
Java codes needs to be complied Java Script code all in text they require different plug-in.
Java Script 6
Nandha Arts and Science College PHP – I Unit BCA Department
SYNTAX OF JAVASCRIPT
<SCRIPT>
Statements; </Script> (or)
<SCRIPT language = “JavaScript”>
Statements; </Script> (or)
<Script Language = "JavaScript" type = "text/JavaScript">
Java script code; </Script>
The script tag takes are important attributes:
• Language − This attribute specifies what scripting language you are using. Typically, its value will be JavaScript.
Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting language in use and its value
should be set to "text/JavaScript".
• src − The location of an external scripting file
Example – 01
<html> <title> Java Script Program </title>
<body>
<script language="JavaScript" type ="text/JavaScript">
<!--
document.write("This is My First JavaScript Program");
//-->
</script>
This is My First
</body> JavaScript Program
</html>
Java Script 7
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 02
<Html>
<title> My detail </title>
<body>
<Script language="JavaScript" type="text/JavaScript">
<!--
document.write("Name: Raja")<<"br/">
document.write<"DOB: 22-01-1996")<<"br/">
document.write<"Aim: Program Developer">
//--> Name: Raja
</script> DOB: 22-01-1996
</body> Aim: Program Developer
</html>
Example – 03
<html> Enter the First No. : 10
Enter the Second No. : 20
<title>Add two Number</title> Sum = 30
<body>
<Script language="JavaScript "type="text/JavaScript">
<! -- var N1,N2,sum;
N1= prompt("Enter the First No")
N2 = prompt("Enter the Second No")
Sum = parseInt (N1)+ parseInt(N2) alert ("sum="+sum)
//-->
</Script>
</body>
</html>
Java Script 8
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 04
<html> <title> Arithmetic </title>
<body> <script language="java script" type="text/JavaScript">
<!-- var N1, N2, Sum, Sub, Mul, Div;
N1 = prompt("Enter the First Number:")
N2 = prompt("Enter the Second Number:")
Sum = parseInt(N1) + parseInt(N2)
Sub = parseInt(N1) - parseInt(N2) Enter the First No. : 20
Enter the Second No.: 10
Mul = parseInt(N1) * parseInt(N2)
Sum = 30
Div = parseInt(N1) / parseInt(N2) Subtract = 10
alert("SUM =" + Sum) Multiply = 200
alert("SUB =" + Sub) Division = 2
Java Script 9
Nandha Arts and Science College PHP – I Unit BCA Department
Example - 05
<html> <body>
<script language = "javascript" type = "text/javascript">
<!-- document.write("Hello World!") //-->
Script Enabled
</script>
<noscript> Sorry...JavaScript is needed to go ahead. </noscript>
</body> </html>
Java Script 10
Nandha Arts and Science College PHP – I Unit BCA Department
Now, if the user's browser does not support JavaScript or JavaScript is not enabled, then the message from
</noscript> will be displayed on the screen.
<html> <head>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- functionsayHello()
{ alert("Hello World") }
//--> </script> </head> <body>
<input type="button" onClick="sayHello()" value= "Say Hello"/>
</body> </html>
Example - 07
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
Welcome
<!-- document.write("Welcome to JavaScript") to
//--> JavaScript
</script>
<p>This is web page body </p>
</body> </html>
Java Script 11
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 09 // functions.js
function multiply(num1, num2) 12
{ return num1*num2; }
//Index1.html
<html> <head>
<title> JavaScript Example</title>
<script language = “JavaScript" src="functions.js">
</script> </head>
<body>
<script type="text/JavaScript">
document.write(multiply(3,4));
</script> </body> </html>
Java Script 12
Nandha Arts and Science College PHP – I Unit BCA Department
JAVASCRIPT –VARIABLES
One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language. Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword,
Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names can also begin with $ and _ (but we will not use it in this tutorial)
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names
<script language = “JavaScript” type=“text/JavaScript”>
<!--
var money; (or) var money, name; (or)var money= 5000.00;
var name; var name= “Raja”;
//--> </script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of
variable creation or at a later point in time when you need that variable.
Java Script 13
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 10
<script language = "Java Script” type ="text/Java Script">
<!—
var myvar= "Global" //declare a global variable
function classA() myvar: Local
{ MYVAR: Global
var myvar = "Local" // declare a local variable
document.write("myvar"+ myvar); }
document.write(“MYVAR” + myvar);
//-->
</script>
Java Script 14
abstract delete function null throw
boolean do goto package throws
break double if private transient
byte else implements protected true
case enum import public try
catch export in return typeof
char extends instanceof short var
class false int static void
const final interface super volatile
continue finally long switch while
debugger float native synchronized with
default for new this
JAVASCRIPT - OPERATORS
WHAT IS AN OPERATOR?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following types of operators.
1. Arithmetic Operators
2. Comparison Operators
3. Logical (or Relational) Operators
✓ Bitwise Operator
4. Assignment Operators
5. Miscellaneous Operators
✓ Conditional (or Ternary) Operators
✓ Typeof operator
Example - 11
<html> results= a * b;
<body> document.write(results);
<!— a =++a;
document.write(“Arithmetic document.write(results);
document.write(results); results=--b;
document.write(linebreak); document.write(results);
results= a - b; //-->
document.write(results); </script>
document.write(linebreak); </body>
results= a / b;
document.write(results);
document.write(linebreak);
document.write("a * b = ");
Java Script 16
Nandha Arts and Science College PHP – I Unit BCA Department
Example -12
<html>
<body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- document.write(results);
var a =10, b =20 results; document.write("(a >= b) => ");
var linebreak="<br />"; results = (a >= b);
document.write(“Comparison document.write(results);
Operations Program”); document.write("(a <= b) => ");
document.write("(a == b) => "); results = (a <= b);
results = (a == b); document.write(results);
document.write(results); document.write(linebreak);
document.write(linebreak); //--> </script> </body> </html>
document.write("(a < b) => ");
results = (a < b);
Comparison Operator Program
document.write(results); Output
(a == b) => false
document.write("(a > b) => ");
(a < b) => true
results = (a > b); (a > b) => false
(a != b) => true
document.write(results); (a >= b) => false
document.write("(a != b) => "); a <= b) => true
results = (a != b);
Java Script 17
Nandha Arts and Science College PHP – I Unit BCA Department
&& "AND" operator. If both operands are non-zero then condition becomes true. (A&&B) = True
||
"OR" operator is any one operandis non-zero then condition becomes true. (A||B) =True
! "!" operator called logical not operator. Use to reserves the logical operator make false. !(A&&B) = False
Example – 13
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!--
var a = true, b =false results; document.write(linebreak);
var linebreak="<br />"; document.write("!(a && b) => ");
document.write(“Logical Or results=(!(a && b));
Relational Operator”); document.write(results);
document.write("(a && b) => "); document.write(linebreak);
results=(a && b); //--> </script> </body> </html>
document.write(results);
document.write(linebreak); Logical or Relational Operator
document.write("(a || b) => ");
results=(a || b); (a&& b) => false (a || b) => true !(a && b) => true
document.write(results);
& Bitwise "AND" operator. It performs a Boolean AND operation on each bit of its integer (A&B) is 2
argument.
| Bitwise "OR" operator. It performs a Boolean OR operation on each bit of its integer (A|B) is 3.
argument.
A Bitwise "XOR" operator. It performs a Boolean Exclusive OR operation on each bit of its (AAB) is 1.
integer argument.
~ Bitwise "NOT" operator. It unary operator and operates by reversing all bits in the operand. (~B) is -4
<< Bitwise "Shift Left Operator" It moves all bits in its first operand to the left by the number (A<<1) is 4
of places specified in the second operand.
>> Bitwise "Shift Right Operator" It moves all bits in its first operand to the right by the (A>>1) is 1.
number of places specified in the second operand.
>>> Bitwise "Shift Right with Zero Operator. This operator just like the >> operator, except that (A>>>1) is 1.
the bits shifted in on the left are always zero.
Java Script 18
Nandha Arts and Science College PHP – I Unit BCA Department
(A<<1) 00100
4 (A>>1) 00010
1
0 left to right
side move
(A<<1) 0100 4 (A>>1) 0001 1
A=5 (>>>) A = 10 (>>>)
A = 0101 5 A = 1010 10
2 5
(A>>>5) 00101 (A>>>5) 01010
Java Script 19
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 14
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!--
var a =2;// Bit presentation 10 results=(~b);
var b =3;// Bit presentation 11 document.write(results);
var results, linebreak="<br />"; document.write(linebreak);
document.write(“Bitwise operator”); document.write("(a << 1) => ");
document.write("(a & b) => "); results=(a << b);
results=(a & b); document.write(results);
document.write(results); document.write(linebreak);
document.write(linebreak); document.write("(a >> 1) => ");
document.write("(a | b) => "); results=(a >> b);
results=(a | b); document.write(results);
document.write(results); document.write(linebreak);
document.write(linebreak); //--> </script> </body> </html>
document.write("(a ^ b) => ");
results=(a ^ b); Bitwise operator
document.write(results); (a& b) => 2 (a | b) => 3
document.write(linebreak); (a ^ b) => 1 (~b) => -4
document.write("(~b) => "); (a << 1) => 4 (a >>1) => 1
4. ASSIGNMENT OPERATOR:
Operator Description Example
= Assigns values from right side operands to left side operand. C=A+B will assign value of A+B into C
+= Add AND assignment operator, it adds right operand to the left C+= A is equal to C=C+A
operand and assign the results to left operand.
-= Subtract AND assignment operator, it Subtract right operand to C-= A is equal to C=C-A
the left operand and assign the results to left operand.
*= Multiply AND assignment operator, it Multiplies right operand C*= A is equal to C=C*A
to the left operand and assign the results to left operand.
/= Divide AND assignment operator, it divides left operand with C/= A is equal to C=C/A
the right operand and assign the results to left operand.
%= Modulus AND assignment operator, it takes modulus using two C%=A is equal to C=C%A
operands and assign the results to left operand.
Java Script 20
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 15
<html> <body> <script language = “JavaScript” type=“text/JavaScript”>
<!-- document.write("Value of a => (a *= b) => ");
Example – 16
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var a =1, b =2; var linebreak="<br />";
document.write("((a > b) ?50 : 100) => ");
results=(a > b)?50:100; Output
document.write(results); ((a > b) ? 50 : 100) => 100
document.write(linebreak); ((a < b) ? 50 : 100) => 50
document.write("((a < b) ?50 : 100) => ");
results=(a < b)?50:100;
document.write(results); //--> </script> </body> </html>
Java Script 21
Nandha Arts and Science College PHP – I Unit BCA Department
Number "number"
String "string"
Boolean "Boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example – 17
The following code shows how to implement typeof operator.
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”> Output
<!-- Result => y is String
var x =10, y ="String";
Result => x is Numeric
var linebreak="<br />";
results=(typeof y =="string"?" y is String": "y is Numeric");
document.write("Result => ");
document.write(results);
document.write(linebreak);
results=(typeof x =="string"? "x is String": "x is Numeric");
document.write("Result => ");
document.write(results);
document.write(linebreak);
//-->
</script>
</body>
</html>
Java Script 22
Nandha Arts and Science College PHP – I Unit BCA Department
• if...else statement
IF STATEMENT
The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.
Syntax The syntax for a basic if statement is as follows −
If (expression) { Statement(s) to be executed if expression is true }
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are executed. If
the expression is false, then no statement would be not executed. Most of the times, you will use comparison
operators while making decisions.
Example – 18
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!--
var age =20;
Output
if( age >18){
document.write("<b> Qualifies for driving</b>"); Qualifies for driving
IF...ELSE STATEMENT:
The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in
a more controlled way.
Syntax
if(expression){
Statement(s) to be executed if expression is true
}
else {
Statement(s) to be executed if expression is false
}
Java Script 23
Nandha Arts and Science College PHP – I Unit BCA Department
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the ‘if’ block,
are executed. If the expression is false, then the given statement(s) in the else block are executed.
Example – 19
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var age =15;
if(age>18) Output
{ Does not qualify for
document.write("<b>Qualifies for driving</b>"); driving
}
else
{
document.write("<b>Does not qualify for driving</b>");
}
//--> </script> </body> </html>
Java Script 24
Nandha Arts and Science College PHP – I Unit BCA Department
There is nothing special about this code. It is just a series of if statements, where each if is a part of the else
clause of the previous statement. Statement(s) are executed based on the true condition, if none of the
conditions is true, then the else block is executed.
Example – 20
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var book ="C";
if( book =="C++"){
document.write("<b> C++ Book</b>"); Output
} C Book
elseif( book =="Java"){
document.write("<b> Java Book</b>");
}
elseif( book =="C"){
document.write("<b> C Book</b>");
}
else{
document.write("<b>Unknown Book</b>");
}//--> </script> </body> </html>
Java Script 25
Nandha Arts and Science College PHP – I Unit BCA Department
switch(expression)
{
case condition 1:
statement(s)
break;
case condition 2:
statement(s)
break;
...
case condition n:
statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter would
continue executing each statement in each of the following cases.
Example – 21
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var grade='A';
document.write("Entering switch block <br />");
switch(grade)
{ Output
case'A':document.write("Gold Medal <br />");
break;
Entering switch block
case'B':document.write("Distinction <br />");
Gold Medal
break;
Exiting switch block
case'C':document.write("First Class <br />");
break;
case'D':document.write("Second Class <br />");
break;
case'E':document.write("Third Class <br />");
break;
case'F':document.write("Failed <br />");
break;
default: document.write("Unknown grade <br />")
}
document.write("Exiting switch block");
//--> </script> </body> </html>
Java Script 26
Nandha Arts and Science College PHP – I Unit BCA Department
BREAK STATEMENTS
Break statements play a major role in switch-case statements. Try the following code that uses switch-case
statement without any break statement.
Example – 22
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”>
<!-- var grade='A';
document.write("Entering switch block<br />");
Output
switch(grade){
Entering switch block
case'A':document.write("Gold Medal <br />"); Gold Medal
Distinction
case'B':document.write("Distinction <br />");
First Class
case'C':document.write("First Class <br />"); Second Class
Third Class
case'D':document.write("Second Class <br />"); Failed
case'E':document.write("Third Class <br />"); Unknown grade
Exiting switch block
case'F':document.write("Failed <br />");
default:document.write("Unknown grade <br />")
}document.write("Exiting switch block");
//--> </script> </body> </html>
Java Script 27
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 23
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”> Output
Example – 24
<html> <body>
<script language = “JavaScript” type=“text/JavaScript”> <!-- var count =0;
document.write("Starting Loop"+"<br />");
do{
document.write("Current Count : "+ count +"<br />");
count++;
}while(count <5);
document.write("Loop stopped!");
//--> </script> </body> </html>
Java Script 28
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 25
<html> <body> Starting Loop
<script type=“text/JavaScript”> Current Count : 0
Current Count : 1
<!-- var count; Current Count : 2
document.write("Starting Loop"+"<br />"); Current Count : 3
Current Count : 4
for(count =0; count <10; count++){
Current Count : 5
document.write("Current Count : "+ count ); Current Count : 6
document.write("<br />"); Current Count : 7
Current Count : 8
} Current Count : 9
document.write("Loop stopped!"); Loop stopped!
//--> </script> </body> </html>
Java Script 29
Nandha Arts and Science College PHP – I Unit BCA Department
A for...in loop only iterates over enumerable properties. Objects created from built–in constructors
like Array and Object have inherited non–enumerable properties from Object.prototype and
String.prototype.
The for loop is very useful when you already know how many times a piece of code should run. In
JavaScript for loop iterates through each and every item in an array. Arrays in JavaScript are zero-
based, that means array’s first item’s index number will be 0 and so on as mentioned below in the
screenshot.
Syntax
for (variable in object)
{
code to be executed
}
Variable : A different property name is assigned to variable on each iteration.
Object : Object whose enumerable properties are iterated. In each iteration, one property from object is assigned to
variable name and this loop continues till all the properties of the object are exhausted .
Javascript forEach method calls a provided function for each and every element in an array.
arrayName.forEach(function(currentValue, index, array), thisValue)
JavaScript forEach() Method – Parameter Values
currentValue is a required argument. It represents the value of the current item in an array.
Index is an optional parameter. It represents the current element in an array.
Array is an optional parameter. This array represents the current element which belongs to the array object.
thisValue this parameter is an optional parameter. It represents the used values when executing the callback
Example
var namesArray = ['Rose', 'Lilly', 'Jasmine', 'Lotus', 'Tulip']; Rose
Lilly
namesArray.forEach(function(data)
Jasmine
{ Lotus
Tulip
console.log(data);
})
Java Script 30
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 26
console object commands
Output
<html>
This table shows the syntax for the
<body> "obj. a = 1"
console object commands that you
<script > “obj. b = 2" can use in the JavaScript Console
window, or that you can use to send
<!-- "obj. c = 3" messages to the console from your
var obj = {a:1, b:2, c:3}; code. This object provides a number
of forms so that you can distinguish
for (var prop in obj) { between informational messages
and error messages, if you want to.
console.log("obj." + prop + " = " + obj[prop]);
You can use the longer command
}
form window.console[command] if
</script> you need to avoid possible
confusion with local objects named
</body> console.
</html>
Example – 27
<html>
<body>
<h2> JavaScript Loops</h2>
<p> The for/in statement loops through the properties of an object.</p>
<p id="demo"> </p>
<script>
var txt = "";
var person = {fname:"Karthick", lname:"Raja, age:25};
JavaScript Loops
var x; The for/in
for (x in person) statement loops
through the
{ properties of an
object.
txt += person[x] + " ";
Karthick Raja 25
}
document.getElementById("demo").innerHTML = txt;
</script> </body> </html>
Java Script 31
Nandha Arts and Science College PHP – I Unit BCA Department
To handle all such situations, JavaScript provides break and continue statements. These statements are used
to immediately come out of any loop or to start the next iteration of any loop respectively.
Example – 28
<html>
<body>
Output
<script type=“text/JavaScript”>
<!--
Entering the loop
var x =1;
2
document.write("Entering the loop<br /> "); 3
while(x <20) 4
{ 5
if(x ==5)
{
break;// breaks out of loop completely
}
x = x +1;
document.write(x+"<br />");
}
document.write("Exiting the loop!<br /> ");
//--> </script> </body> </html>
Java Script 32
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 29
<html> <body>
<script type=“text/JavaScript”>
Output
<!--var x =1;
Entering the loop
document.write("Entering the loop<br /> ");
2
while(x <10) 3
{ 4
x = x +1; 6
if(x ==5) 7
8
{ continue;
9
} 10
document.write( x+"<br />"); Exiting the loop!
}
document.write("Exiting the loop!<br /> ");
//--> </script> </body> </html>
Java Script 33
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 30
<html> <body>
<script>
function getcube(number){
alert(number * number * number);
} </script> <form>
<input type="button" value="click" onClick="getcube(4)"/>
</form> </body> </html>
Return Statement:
Java Script function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement is a function.
function firstfunction(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = firstfunction ('Sumathi', 'Raja');
document.write (result );
}
Java Script 34
Nandha Arts and Science College PHP – I Unit BCA Department
onClick: Use this to invoke JavaScript upon clicking (a link, or form boxes)
onload: Use this to invoke JavaScript after the page or an image has finished loading.
onmouseover: Use this to invoke JavaScript if the mouse passes by some link
onmouseout: Use this to invoke JavaScript if the mouse goes pass some link
onunload: Use this to invoke JavaScript right after someone leaves this page.
Java Script 35
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 32
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
Java Script 36
Nandha Arts and Science College PHP – I Unit BCA Department
function myFunction()
{
alert("The form was submitted");
}
</script>
</body>
</html>
Example – 33
<html> <head>
<script type="text/JavaScript">
<!--
function popup()
{
alert("Hello World")
} //--> </script> </head>
<body>
<input type="button" value="Click Me!" onClick="popup()"><br />
Hover Me!</a> </body> </html>
Java Script 37
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 34
<button onClick = “Myfunction (‘Karthik’,‘Raja’)“> tryit>
</button>
<Script language=”java script” type=”text/java script”>
<!-- function myfunction(fname, lname)
{ alert (“welcome” +fname+ ” “ +lname);
} // -- > </script> Output
Welcome Karthik Raja
Function with a return value:
Syntax:
function funtion name()
{ statements;
return ; }
Something you want your function return a value back to where call was mode this possible by using return statement.
Java Script 38
Nandha Arts and Science College PHP – I Unit BCA Department
Java Script 39
Nandha Arts and Science College PHP – I Unit BCA Department
Java Script 40
Nandha Arts and Science College PHP – I Unit BCA Department
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax: var array_name = [item1, item2,..];
The Array parameter is a list of strings or integers. When you specify
a single numeric parameter with the Array constructor, you specify
the initial length of the array. The maximum length allowed for an
array is 4,294,967,295.
Example 36
<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
var cars = ["Benz","Volvo","BMW"];
document.write(cars);
</script>
</body>
</html>
JavaScript Arrays
Benz, Volvo, BMW
Array Properties
Here is a list of the properties of the Array object along with their description.
Property Description
constructor Returns a reference to the array function that created the object.
index The property represents the zero-based index of the match in the string
input This property is only present in arrays created by regular expression matches.
length Reflects the number of elements in an array.
prototype The prototype property allows you to add properties and methods to an object.
JavaScript Class:
A JavaScript class is a type of function. Classes are declared with the class keyword. We can use class
expression syntax to initialize the class.
We can define a class with the following syntax of JavaScript.
Java Script 41
Nandha Arts and Science College PHP – I Unit BCA Department
JavaScript Objects:
• Objects in JavaScript are its most important data type and forms the building blocks for modern
JavaScript. These objects are quite different from JavaScript’s primitive data types (Numbers, String,
Boolean, Null, Undefined, Symbol) in the sense that while these primitive data types all store a single
value each (depending on their types).
• An object is also a reference data type. Variables as a reference value are given a reference or a pointer
to that value. The variables don’t actually store the value.
• Objects in JavaScript may be defined as an unordered collection of related data or primitive or
reference types, in the form of “key: value” pairs. These keys can be variable or functions and are
called Properties and Methods, in the context of an object.
• In JavaScript, almost ‘Everything’ is an object. If defined with “new” keyword.
Example 38
<script>
class User
{ Karthi
constructor(name)
{
this.name = name;
}
sayHi()
{
alert(this.name);
}
}
Java Script 42
Nandha Arts and Science College PHP – I Unit BCA Department
// Usage:
user = new User("Karthi");
user.sayHi();
</script>
You can use object properties 2 ways:
Example
1. Name = person.lastname; 2. Name = person(“lastname”);
Undefined and null
Undefined is value of a variable no value, Variable can be empty by setting value to be null.
Example cars=null;
Java Script 43
Nandha Arts and Science College PHP – I Unit BCA Department
Example 38
user = { user = {
name: "JANU", J name: "JANU", h
age: 30, A age: 30, }; e
sayHi() N user.sayHi() = funtion() ll
{ { o
U
alert(this.name); alert(“hello”);
} };
}; user.sayHi();
user.sayHi(); </script>
</script>
JAVA SCRIPT ERRORS & EXCEPTIONS HANDLING
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors and (c) Logical Errors.
a) SYNTAX ERRORS
Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and
at interpret time in JavaScript.
Example the following line causes a syntax error because it is missing a closing parenthesis.
<script language = “JavaScript” type="text/JavaScript">
<!--
window.print();
//--> </script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax
error is affected and the rest of the code in other threads gets executed assuming nothing in them depends
on the code containing the error.
b) RUNTIME ERRORS
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but at runtime,
it is trying to call a method that does not exist.
<script language = “JavaScript” type="text/JavaScript">
<!-- window.printme(); //--> </script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.
c) LOGICAL ERRORS
Logic errors can be the most difficult typeof errors to track down. These errors are not the results of a
syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script
and you do not get the results you expected.
Java Script 44
Nandha Arts and Science College PHP – I Unit BCA Department
You cannot catch those errors, because it depends on your business requirement what type of logic you
want to put in your program.
Java Script 45
Nandha Arts and Science College PHP – I Unit BCA Department
{
var a = 100;
try {
document.write("Value of variable a is : " + a );
}
catch (e) {
document.write ("Error: " + e.description );
}
} Definition: - The getElementById()
method returns the element that
//--> has the ID attribute with the
</script> specified value. This method is
one of the most common
</head> methods in the HTML DOM, and is
<body> used almost every time you want
to manipulate, or get info from, an
<p>Click the following to see the result:</p> element on your document.
<form> Definition:- The Document Object
<input type="button" value="Click Me" Model (DOM) is a programming
API for HTML and XML
onClick="myFunc();" /> documents. It defines the logical
structure of documents and the
</form>
way a document is accessed and
</body> </html> manipulated.
Java Script 46
Nandha Arts and Science College PHP – I Unit BCA Department
Syntax:
Throw exception
Exception can be java script string, number, Boolean or an objects.
Example – 40
<html>
Click the following to see the result:
<head>
<script type="text/JavaScript">
<!-- Value of variable a is: 100
function myFunc()
{ Finally block will always execute!
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch (e) {
alert("Error: " + description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p> Click the following to see the result:</p>
<form>
<input type= "button" value= "Click Me" onClick= "myFunc();" />
</form>
</body>
</html>
---x---x---x---
Java Script 47
Unit-I
Features of VBScript
• VBScript is a lightweight scripting language, which has a lightning fast interpreter.
• VBScript, for the most part, is case insensitive. It has a very simple syntax, easy to learn and to
implement.
• Unlike C++ or Java, VBScript is an object-based scripting language and NOT an Object-Oriented
Programming language.
• It uses Component Object Model (COM) in order to access the elements of the environment in
which it is executing.
• Successful execution of VBScript can happen only if it is executed in Host Environment such as Internet
Explorer (IE), Internet Information Services (IIS) and Windows Scripting Host (WSH)
Disadvantages
• VBScript is used only by IE Browsers. Other browsers such as Chrome, Firefox don’t Support
VBScript.
• VBScript has a Limited command line support.
• Since there is no development environment available by default, debugging is difficult.
Example – 41
<html> My First
<body> VBScript Program
<script language="vbscript"
type="text/vbscript">
document.write("My First VBScript Program")
</script>
</body>
</html>
Formatting
VBScript is based on Microsoft's Visual Basic. Unlike JavaScript, no statement terminators such as
semicolon is used to terminate a particular statement.
VB Script
49
Nandha Arts and Science College PHP – I Unit BCA Department
RESERVED WORDS
And Eqv LSet Resume
As Erase Me RSet
Boolean Eval Mod Select
ByRef Event Msgbox SendKeys
Byte Execute New Set
ByVal ExecuteGlobal Next Shared
Call Exit Not Single
Case FALSE Nothing Static
Class For Null Stop
Const Function On Sub
Currency Get Option Then
Debug GoTo Option Explicit To
Dim If Optional TRUE
Do Imp Or Type
Double Implements ParamArray TypeOf
Each In Preserve Until
Else Integer Private Variant
ElseIf Is Public Wend
Empty Let RaiseEvent While
End Like Randomize With
EndIf Long ReDim Xor
Enum Loop Rem
CASE SENSITIVITY
VBScript is a case-insensitive language. This means that language keywords, variables, function names
and any other identifiers need NOT be typed with a consistent capitalization of letters. So identifiers
int_counter, INT_Counter and INT_COUNTER have the same meaning within VBScript.
VB Script
50
Nandha Arts and Science College PHP – I Unit BCA Department
COMMENTS IN VBSCRIPT
Comments are used to document the program logic and the user information with which other
programmers can seamlessly work on the same code in future. It can include information such as
developed by, modified by and it can also include incorporated logic. Comments are ignored by the
interpreter while execution. Comments in VBScript are denoted by two methods.
Any statement that starts with a Single Quote (‘) is treated as comment. Following is the example:
<script language="vbscript" type="text/vbscript">
<!--
' This Script is invoked after successful login
' Written by : karthik
' Return Value : True / False
//-- > </script>
Any statement that starts with the keyword “REM”. Following is the example:
<script language="vbscript" type="text/vbscript">
<!--
REM This Script is written to Validate the Entered Input
//-- > </script>
VB Script
51
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 43
<html> <head>
<script type="text/Vbscript">
<!--
function sayHello()
Msgbox("Hello World")
End Function
//--> </script> </head>
<body>
<input type="button" onClick= "sayHello()" value= "Say Hello" />
</body> </html>
you would not have any function defined using VBScript: This is web page
Example – 44
<html>
<body>
<script type="text/vbscript">
<!
document.write("VBScript Body Section")
//-->
</script>
<p> This is web page </p>
</body> </html>
VB Script
52
Nandha Arts and Science College PHP – I Unit BCA Department
Function sayHello()
msgbox("Hello World")
End Function
//-->
</script> </head> <body>
<script type="text/vbscript">
<!-- document.write("Hello World")
//-->
</script>
<input type="button" onClick="sayHello()" value="Say Hello" />
</body> </html>
Example – 46
<html> <head>
<script language = “Javascript” type="text/vbscript" src="filename.vbs">
</script> </head>
<body> ....... </body> </html>
To use VBScript from an external file source, you need to write your all VBScript source code in a
simple text file with extension ".vbs" and then include that file as shown above. For Eg:-, you can keep
the following content in filename.vbs file and then you can use sayHello function in your HTML file
after including filename.vbs file.
Function sayHello()
Msgbox "Hello World"
End Function
VBScript Variables
A variable is a named memory location used to hold a value that can be changed during the script
execution. VBScript has only one fundamental data type, Variant.
VB Script
53
Nandha Arts and Science College PHP – I Unit BCA Department
Dim
Variables declared using “Dim” keyword at a Procedure level are available only within the same
procedure. Variables declared using “Dim” Keyword at script level are available to all the procedures
within the same script.
Example: In the below example, the value of Var1 and Var2 are declared at script level while Var3 is declared
at procedure level.
VB Script
54
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 47
<html>
<body>
<script language="vbscript" 25 15
type="text/vbscript">
<!--
Dim Var1, Var2
Call add()
Function add()
10
Var1 = 10
Var2 = 15
Dim Var3
Var3 = Var1+Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1 ' Displays 10 as Var1 is declared at Script level
Msgbox Var3 ' Var3 has No Scope outside the procedure. Prints Empty
//-->
</script>
</body>
</html>
Public
Variables declared using "Public" Keyword are available to all the procedures across all the associated scripts.
When declaring a variable of type "public", Dim keyword is replaced by "Public".
Example: Var1 and Var2 are available at script level while Var3 is available across the associated scripts and
procedures as it is declared as Public.
Example – 48
<html>
<head> <title> Variables declared using public </title> </head>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Dim Var1, Var2
Public Var3
Call add()
VB Script
55
Nandha Arts and Science College PHP – I Unit BCA Department
Function add()
Var1 = 100
Var2 = 150
Var3 = Var1+Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1 ' Displays 100 as Var1 is declared at Script level
Msgbox Var2 ' Displays 150 as Var2 is declared at Script level
Msgbox Var3 ' Displays 250 as Var3 is declared as Public
//-->
</script> Var1
Var3
</body>
</html> 250 100
Var2 Var3
150 250
Private
Variables that are declared as "Private" have scope only within that script in which they are declared.
When declaring a variable of type "Private", Dim keyword is replaced by "Private".
Example – 49
Var1 and Var2 are available at Script Level. Var3 is declared as Private and it is available only for this particular script. Use
of "Private" Variables is more pronounced within the Class.
<html>
<head>
<title> Variables that are declared as "Private" </title>
</head>
<body>
<script language="vbscript" type="text/vbscript">
Dim Var1, Var2
Private Var3
Call add()
VB Script
56
Nandha Arts and Science College PHP – I Unit BCA Department
Function add()
Var1 = 1000
Var2 = 1500
Var3 = Var1+Var2
Msgbox Var3 'Displays the sum of two values.
End Function
Msgbox Var1 ' Displays 1000 as Var1 is declared at Script level
Msgbox Var2 ' Displays 1500 as Var2 is declared at Script level
Msgbox Var3 ' Displays 2500 but Var3 is available only for this script.
</script>
</body> Var3 Var1
</html>
2500 1000
Var3
Var2
1500 2500
Constant is a named memory location used to hold a value that CANNOT be changed during the
script execution. If a user tries to change a Constant Value, the Script execution ends up with an
error. Constants are declared the same way the variables are declared.
Declaring Constants
Syntax : [Public | Private] Const Constant_Name = Value
The Constant can be of type Public or Private. The Use of Public or Private is Optional. The Public
constants are available for all the scripts and procedures while the Private Constants are available
within the procedure or class. One can assign any value such as number, String or Date to the declared
Constant.
Example – 50
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
VB Script
57
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 51
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Const myString = "VBScript"
Const myDate = #01/01/2050#
Msgbox myString VBScript 01-01-2050
Msgbox myDate
//-->
</script>
</body> </html>
What is an Operator?
Let’s take an expression 4 + 5 is equal to 9. Here, 4 and 5 are called operands and + is called the
operator. VBScript language supports following types of operators:
• Arithmetic Operators • Logical (or Relational) Operators
• Comparison Operators • Concatenation Operators
VB Script
58
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 52
<html> <body> <script language="vbscript" type="text/vbscript">
<!--
dim a = 5, b = 10, c;
c = a+b
Result
document.write ("Addition Result is " &c)
document.write (“<br>“) Addition Result is 15
c = a-b Subtraction Result is -5
The Comparison Operators Assume variable A holds 10 and variable B holds 20, then:
VB Script
59
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 53
<html> <body>
<script language="vbscript" type="text/vbscript">
<!--
dim a,b,c; a = 10,b = 20,c;
If a=b Then
document.write ("Operator Line 1 : True")
else
document.write ("Operator Line 1 : False") Operator Line 1 : False
VB Script
60
Nandha Arts and Science College PHP – I Unit BCA Department
The Logical Operators Assume variable A holds 10 and variable B holds 0, then:
VB Script
61
Nandha Arts and Science College PHP – I Unit BCA Department
The Concatenation Operators Assume variable A holds 5 and variable B holds 10 then:
if..else statement An if else statement consists of a Boolean expression followed by one or more
statements. If the condition is True, the statements under the If statements are
if...elseif..else executed.
An If the condition
if statement is false,
followed by one orthen theElseIf
more Else part of the script
Statements, that isconsists
Executedof Boolean
statement expressions and then followed by an optional else statement, which executes when
switch statement A switch statement allows a variable to be tested for equality against a list of values.
VB Script
62
Nandha Arts and Science College PHP – I Unit BCA Department
If Statements
An If statement consists of a Boolean expression followed by one or more statements. If the
condition is said to be True, the statements under If condition(s) are Executed. If the Condition is
said to be False, the statements after the If loop are executed.
Syntax The syntax of an If statement in VBScript is:
If(boolean_expression) Then
Statement 1
.....
Statement n
End If
Example – 56
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
dim a = 11,b = 10;
if a > b Then
document.write ("A is Greater than B" );
end If
//-->
</script> a is Greater than B
</body>
</html>
If…Else Statements
An If statement consists of a Boolean expression followed by one or more statements. If the
condition is said to be True, the statements under If condition(s) are Executed. If the Condition is
said to be False, the statements under Else Part would be executed.
VB Script
63
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 57
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Dim a ; a = 5
Dim b ; b = 25
If a > b Then
b is Greater
document.write("a is Greater")
Else
document.write ("b is Greater")
End If
//-->
</script>
</body>
</html>
If(boolean_expression) Then
Statement 1
..... ..... Statement n
ElseIf (boolean_expression) Then
Statement 1
......... Statement n
ElseIf (boolean_expression) Then
Statement 1
......... Statement n
Else
Statement 1
......... Statement n
End If
VB Script
64
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 58
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a a is a NEGATIVE Number
a = -5
If a > 0 Then
document.write (“a is a POSITIVE Number")
ElseIf a < 0 Then
document.write (“a is a NEGATIVE Number")
Else
document.write (“a is EQUAL than ZERO"
End If
//--> </script> </body> </html>
Nested If Statement
If or ElseIf statement inside another If or ElseIf statement(s). The Inner If statements are executed based on
the Outermost If statements. This enables VBScript to handle complex conditions with ease.
Example – 59
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
dim a = 5;
if a > 0 Then
document.write (“The Number is a POSITIVE Number")
if a = 1 Then
document.write (“The Number is Neither Prime NOR Composite")
elseif a = 2 Then
document.write (“The Number is the Only Even Prime Number")
elseif a = 3 Then
document.write (“The Number is the Least Odd Prime Number")
else
document.write (“The Number is NOT 0,1,2 or 3")
end If
elseIf a < 0 Then
document.write (“The Number is a NEGATIVE Number")
else
document.write (“The Number is ZERO")
end If
//--> </script> </body> </html>
Switch Statements
When a user wants to execute a group of statements depending upon a value of an expression, then
he can use Switch Case statements. Each value is called a Case, and the variable being switched ON
based on each case. Case Else statement is executed if test expression doesn't match any of the
Case specified by the user.
Case Else is an optional statement within Select Case, however, it is a good programming practice
to always have a Case Else statement.
VB Script
66
Nandha Arts and Science College PHP – I Unit BCA Department
Syntax
Select Case expression
Case expression list 1
statement1
statement2
........ statement n
Case expression list 2
statement1
statement2
........ statement n
Case expression list n
statement1
statement2
........ statement n
.... Case Else
Else
statement1
else
statement2
....
.... End Select
Example – 60
<html> <body> <script language="vbscript" type="text/vbscript">
<!-- The Number is the Least
dim MyVar = 100
Composite Number
Select case MyVar
case 1
document.write("The Number is the Least Composite Number")
case 2
document.write("The Number is the only Even Prime Number")
case 3
document.write("The Number is the Least Odd Prime Number")
case else
document.write ("Unknown Number")
End select
//-->
</script>
</body> </html>
VB Script
67
Nandha Arts and Science College PHP – I Unit BCA Department
VB Script
68
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 61
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!-- dim a : a=15
for i=0 to a Step 3
document.write("The value is i is : " & i)
The value is i is : 0
document.write(“<br>“) The value is i is : 3
The value is i is : 6
next The value is i is : 9
The value is i is : 12
//--> The value is i is : 15
</script> </body> </html>
For...Each Loops
A For Each loop is used when we want to execute a statement or a group of statements for each element in an
array or collection. A For Each loop is similar to For Loop; however, the loop is executed for each element in an
array or group. Hence, the step counter won't exist in this type of loop and it is mostly used with arrays or used
in context of File system objects in order to operate recursively.
VB Script
69
Nandha Arts and Science College PHP – I Unit BCA Department
While...Wend Loop
In a While.. Wend loop, if the condition is True, all statements are
executed until Wend keyword is encountered. If the condition is false,
the loop is exited and the control jumps to very next statement after
Wend keyword.
Example – 63
<html>
<body>
<script type="text/vbscript">
<!--
Dim Counter = 10
While Counter < 15 ' Test value of Counter.
The Current Value: 11
Counter = Counter + 1 ' Increment Counter. The Current Value: 12
Do..While statement
Do..While loop is used when we want to repeat a set of
statements as long as the condition is true. The Condition may be
checked at the beginning of the loop or at the end of the loop.
Syntax The syntax of a Do..While loop in VBScript is:
Do While condition
[statement 1]
[statement 2]
...
[statement n] [Exit Do]
[statement 1]
[statement 2]
...
[statement n] Loop
VB Script
70
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 64
Do..while loop to check the condition at the beginning of the loop. The statements inside the loop
are executed only if the condition becomes True.
<html> <body>
<script language="vbscript" type="text/vbscript">
<!--
The value of i is : 1
Do While i < 5 i = i + 1 The value of i is : 2
Alternate Syntax
There is an alternate Syntax for Do..while loop which checks the condition at the end of the loop. The
Major difference between these two syntax is explained below with an example.
Do
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
Loop While condition
Example – 65
<html> <body> <script language="vbscript"
type="text/vbscript">
<!--
i=10
do{ The value of i is : 11
i = i + 1
document.write("The value of i is : " & i)
document.write("<br>")
loop While i<3 'Condition is false.
VB Script
71
Nandha Arts and Science College PHP – I Unit BCA Department
Syntax
The syntax of a Do..Until loop in VBScript is:
Do Until condition [statement 1]
[statement 2]
...
[statement n] [Exit Do] [statement 1]
[statement 2]
...
[statement n] Loop
Example – 66
The following example uses Do..Until loop to check the condition at the beginning of the loop. The
Statements inside the loop are executed only if the condition is false. It exits out of the loop when
the condition becomes true.
<html>
The value of i is : 11
<body> The value of i is : 12
i=10
Do Until i>15 'Condition is False. Hence loop will be executed
i = i + 1
document.write("The value of i is : " & i)
document.write("<br>")
Loop
//-->
</script>
</body>
</html>
VB Script
72
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 67 Do..Until loop to check the condition at the end of the loop. The Statements inside the
VB Script
73
Nandha Arts and Science College PHP – I Unit BCA Department
Syntax
The syntax for Exit For Statement in VBScript is:
Exit For
Example – 68
The following example uses Exit For. If the value of the
Counter reaches 4, the For Loop is Exited and control jumps to
the next statement immediately after the For Loop.
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
The value is i is : 0
Dim a ; The value is i is : 2
a=10 The value is i is : 4
Exit Do statement
An Exit Do Statement is used when we want to Exit the Do Loops based on certain criteria. It can be
used within both Do..While and Do..Until Loops.
When Exit Do is executed, the control jumps to next statement immediately after the Do Loop.
VB Script
74
Nandha Arts and Science College PHP – I Unit BCA Department
Syntax
The syntax for Exit Do Statement in VBS is: Exit Do
Example – 69
The following example uses Exit Do. If the value of the Counter reaches
10, the Do Loop is Exited and control jumps to the next statement
immediately after the For Loop.
<html>
<body>
<script language="vbscript"
type="text/vbscript">
<!--
i = 0
Do While i <= 100
If i > 10 Then
Exit Do ' Loop Exits if i>10
The Value of i is : 0
End If The Value of i is : 2
document.write("The Value of i is : " &i) The Value of i is : 4
document.write("<br>") The Value of i is : 6
The Value of i is : 8
i = i + 2
The Value of i is : 10
Loop
//-->
</script> </body> </html>
VBScript Procedures
We have two kinds of procedures: The Sub procedure and the Function procedure.
i) Sub procedure:
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that
perform actions but don't return a value. A Sub procedure can take arguments (constants, variables,
or expressions that are passed by a calling procedure).
The following Sub procedure uses two basic, or built-in, VBScript functions, MsgBox and InputBox, to
prompt a user for information. It then displays the results of a calculation based on that information.
The calculation is performed in a Function procedure created using VBScript.
• is a series of statements, enclosed by the Sub and End Sub statements
• can perform actions, but does not return a value
• can take arguments that are passed to it by a calling procedure
• without arguments, must include an empty set of parentheses ()
VB Script
75
Nandha Arts and Science College PHP – I Unit BCA Department
Sub mysub()
some statements
End Sub (or)
Sub mysub(argument1,argument2)
some statements
End Sub
MsgBox Function
Displays a message in a dialog box, waits for the user to click a button, and returns a
value indicating which button the user clicked.
Syntax MsgBox(prompt[, buttons][, title][, helpfile, context])
InputBox Function
Displays a prompt in a dialog box, waits for the user to input text or click a button, and
returns the contents of the text box.
Syntax InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])
ii) Function procedure:
A Function procedure is a series of VBScript statements enclosed by the Function and End Function
statements. A Function procedure is similar to a Sub procedure, but can also return a value. A
Function procedure can take arguments (constants, variables, or expressions that are passed to it by
a calling procedure). If a Function procedure has no arguments, its Function statement must include
an empty set of parentheses. A Function returns a value by assigning a value to its name in one or
more statements of the procedure. The return type of a Function is always a Variant.
is a series of statements, enclosed by the Function and End Function statements
can perform actions and can return a value
can take arguments that are passed to it by a calling procedure
without arguments, must include an empty set of parentheses ()
returns a value by assigning a value to its name
Function myfunction() Function myfunction(argument1,argument2)
Arguments in Procedures
There are two types of arguments in procedures
1) By Val: Indicates that the argument is passed by value.
2) By Ref: Indicates that the argument is passed by reference. By default all arguments are 'ByRef'.
VB Script
76
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 70
Function demo_add(a,b)
demo_add=a+b
End Function
Here ‘a,b’ are the arguments. By default these are 'ByRef'.
In simple terms ‘ByRef’ Means the value which is assigned to the variable with in the function is
permanent and we can use that value out side that function as well.
‘ByVal’ means the value, which is assigned to the variable with in the function, is temporary and we
can use that value only with in that function.
Example – 71
function demo_parameters(byref x,byval y)
x=20 y=50
demo_parameters=x+y
End Function
a=10 b=20
msgbox demo_parameters(a,b)
msgbox a
msgbox b
In the above function ‘x’ and ‘y’ are the arguments, declared as ‘byref’ and ‘byval’. Within that
function we have assigned values to ‘x’ and ‘y’. Outside of the function we have assigned values to
two variables and passing those variables in to the function. Here 'a' is passing reference to x and b
is passing value to y. Within that function we are changing the value for ‘x’. This value is permanent
for 'a' - because 'a' is passed as 'ByRef'. But the value of 'b' will not be changed because it is passed
as 'ByVal'.
What is an Event?
VBScript's interaction with HTML is handled through events that occur when the user or browser
manipulates a page. When the page loads, that is an event. When the user clicks a button, that click
too is an event. Other examples of events include pressing any key, closing window, resizing
window, etc. Developers can use these events to execute VBScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and virtually any
other type of response imaginable to occur. Events are a part of the Document Object Model (DOM)
and every HTML element has a certain set of events, which can trigger VBScript Code.
VB Script
77
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 72
<html> <head>
<script language="vbscript" type="text/vbscript">
<!--
function sayHello()
msgbox "VBScript Events"
end function
//--> </script> </head> <body>
<input type="button" onClick="sayHello()" value="Say Hello"/>
</body> </html>
Example – 73
<html> <body>
<script language="VBScript">
<!--
Function fnSubmit()
Msgbox("Hello Welcome to Nandha Arts ")
End Function
//-->
</script>
<form action="/cgi-bin/test.cgi" method="post"
name="form1"onSubmit="fnSubmit()">
<input name="txt1" type="text"><br>
<input name="btnButton1" type="submit" value="Submit">
</form> //--> </script> </body> </html>
VB Script
78
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 74
<html> <body> <script language="VBScript">
<!--
function AlertMsg()
Msgbox("ALERT !")
End Function
Function onmouse_over()
Msgbox("Onmouse Over")
End Function
Sub txt2_OnMouseOut()
Msgbox("Onmouse Out !!!")
End Sub
Sub btnButton_OnMouseOut()
Msgbox("onmouse out on Button !")
End Sub
//--> </script>
<form action="page.cgi" method="post" name="form1">
<input name="txt1" type="text" OnMouseOut="AlertMsg()"><br>
<input name="txt2" type="text" OnMouseOver="onmourse_over()">
<input name="Button" type="button" value="Submit">
</form> </body> </html>
VB Script
79
Nandha Arts and Science College PHP – I Unit BCA Department
VB Script
80
Nandha Arts and Science College PHP – I Unit BCA Department
What is an Array?
We know very well that a variable is a container to store a value. Sometimes, developers are in a
position to hold more than one value in a single variable at a time. When a series of values is stored
in a single variable, then it is known as an array variable.
Array Declaration
Arrays are declared the same way a variable has been declared except that the declaration of an
array variable uses parenthesis. In the following example, the size of the array is mentioned in the
brackets.
'Method 1 : Using Dim Dim arr1() 'Without Size
'Method 2 : Mentioning the Size Dim arr2(5) 'Declared with size of 5
'Method 3 : using 'Array' Parameter Dim arr3
arr3 = Array("apple","Orange","Grapes")
• Although, the Array size is indicated as 5, it can hold 6 values as array index starts from ZERO.
• Array Index Cannot be Negative.
• VBScript Arrays can store any type of variable in an array. Hence, an array can store an
integer, string or characters in a single array variable.
Example – 75
<html> <body> <script language="vbscript">
<!-- Value stored in Array index 0 : 1
Value stored in Array index 1 : VBScript
Dim arr(5)
Value stored in Array index 2 : 100
arr(0) = "1" Value stored in Array index 3 : 2.45
arr(2) = 100 Value stored in Array index 4 : 7/10/2013
VB Script
81
Nandha Arts and Science College PHP – I Unit BCA Department
Multi-Dimension Arrays
Arrays are not just limited to single dimension and can have a maximum of 60 dimensions. Two-
dimension arrays are the most commonly used ones.
Example – 76 In the following example, a multi-dimension array is declared with 3 rows and 4 columns.
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Dim arr(2,3) ' Which has 3 rows and 4 columns
arr(0,0) = "Apple"
arr(0,1) = "Orange"
arr(0,2) = "Grapes"
arr(0,3) = "pineapple"
arr(1,0) = "cucumber"
arr(1,1) = "beans"
Value stored in Array index: 0, 1: Orange
arr(1,2) = "carrot"
Value stored in Array index: 2, 2: coffee
arr(1,3) = "tomato"
arr(2,0) = "potato"
arr(2,1) = "sandwitch"
arr(2,2) = "coffee"
arr(2,3) = "nuts"
document.write("Value in Array index 0,1 : " & arr(0,1) & "<br />")
document.write("Value in Array index 2,2 : " & arr(2,2) & "<br />")
//-->
</script>
</body> </html>
ReDim Statement
ReDim Statement is used to declare dynamic-array variables and allocate or reallocate storage space.
ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
• Preserve - An Optional parameter used to preserve the data in an existing array when you
change the size of the last dimension.
• varname - A Required parameter, which denotes Name of the variable, which should follow
the standard variable naming conventions.
• subscripts - A Required parameter, which indicates the size of the array.
VB Script
82
Nandha Arts and Science College PHP – I Unit BCA Department
Example – 77
<html>
<body>
<script language="vbscript" type="text/vbscript">
<!--
Dim a()
i=0
redim a(5) a(0)="XYZ" a(1)=41.25 a(2)=22
REDIM PRESERVE a(7) For i=3 to 7 XYZ
a(i)= i 41.25
22
Next 3
'to Fetch the output 4
5
For i=0 to ubound(a) Msgbox a(i) 6
Next 7
//-->
</script> </body> </html>
a) Syntax Errors
Syntax errors, also called parsing errors, occur at interpretation time for VBScript. For example, the
following line causes a syntax error because it is missing a closing parenthesis:
Example – 78
<script type="text/vbscript">
<!--
dim x,y
x = "Vbtutorials" y = Ucase(x)
//-->
</script>
b) Runtime Errors
Runtime errors, also called exceptions, occur during execution, after interpretation.
Example – 79, the following line causes a runtime error because here syntax is correct but at
runtime it is trying to call fnmultiply, which is a non-existing function:
VB Script
83
Nandha Arts and Science College PHP – I Unit BCA Department
<script type="text/vbscript">
<!--
Dim x,y x = 10
y = 20
z = fnadd(x,y)
a = fnmultiply(x,y)
Function fnadd(x,y)
fnadd = x+y
End Function
//-->
</script>
c) Logical errors
Logic errors can be the most difficult type of errors to track down. These errors are not the result of
a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your
script and you do not get the result you expected. You cannot catch those errors, because it depends
on your business requirement what type of logic you want to put in your program. For example,
dividing a number by zero or a script that is written which enters into infinite loop.
Err Object
Assume if we have a runtime error, then the execution stops by displaying the error message. As a
developer, if we want to capture the error, then Error Object is used.
Example – 80 In the following example, Err.Number gives the error number and Err.Description
gives error description.
<script type="text/vbscript">
<!--
Err.Raise 6 ' Raise an overflow error.
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear ' Clear the error.
//-->
</script> STATEMENT
-X-X-X-
VB Script
84
UNIT-II
Parameter Description
Prompt - A Required Parameter. A String that is displayed as a message in the dialog box. The
maximum length of prompt is approximately 1024 characters. If the message extends to
more than a line, then we can separate the lines using a carriage return character.
Buttons - An Optional Parameter. A Numeric expression that specifies the type of buttons to display,
the icon style to use, the identity of the default button, and the modality of the message
box. If left blank, the default value for buttons is 0.
Title - An Optional Parameter. A String expression displayed in the title bar of the dialog box. If
the title is left blank, the application name is placed in the title bar.
Helpfile - An Optional Parameter. A String expression that identifies the Help file to use to provide
context-sensitive help for the dialog box.
Context - An Optional Parameter. A Numeric expression that identifies the Help context number
assigned by the Help author to the appropriate Help topic. If context is provided, help file
must also be provided.
Nandha Arts and Science College PHP – II Unit BCA Department
Example - 81
<html> <body>
<script language="vbscript" type="text/vbscript">
'Message Box with just prompt message
MsgBox("Welcome")
'Message Box with title, yes no and cancel Butttons
a = MsgBox("Do you like blue color?",3,"Choose options")
' Assume that you press No Button
document.write("The Value of a is " & a)
The Value of a is 7
</script></body></html>
VB Script 86
Nandha Arts and Science College PHP – II Unit BCA Department
Syntax
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
Parameter Description
Prompt - A Required Parameter. A String that is displayed as a message in the dialog box. The
maximum length of prompt is approximately 1024 characters.
Title - An Optional Parameter. A String expression displayed in the title bar of the dialog box. If
the title is left blank, the application name is placed in the title bar.
Default - An Optional Parameter. A default text in the text box that the user would like to be displayed.
XPos - An Optional Parameter. The Position of X axis which represents the prompt distance from
left side of the screen horizontally. If left blank, the input box is horizontally centered.
YPos - An Optional Parameter. The Position of Y axis which represents the prompt distance from
left side of the screen vertically. If left blank, the input box is vertically centered.
Helpfile - An Optional Parameter. A String expression that identifies the Help file to use to provide
context-sensitive Help for the dialog box.
Context - An Optional Parameter. A Numeric expression that identifies the Help context number
assigned by the Help author to the appropriate Help topic. If context is provided, help file
must also be provided.
Example-82
<html>
<body>
<script language="vbscript" type="text/vbscript">
' Input Box with only Prompt
InputBox("Enter a number")
' Input Box with a Title
a=InputBox("Enter a Number","Enter Value")
msgbox a
' Input Box with a Prompt,Title and Default value
a=InputBox("Enter a Number","Enter Value",123)
VB Script 87
Nandha Arts and Science College PHP – II Unit BCA Department
msgbox a
' Input Box with a Prompt,Title,Default and XPos
a=InputBox("Enter your name","Enter Value",123,700)
msgbox a
‘ Input Box with a Prompt,Title and Default and YPos
a=InputBox("Enter your name","Enter Value",123,,500)
msgbox a
</script> </body> </html>
File Input/Output:
What are FSO Objects?
As the name suggests, FSO (File System Object) help the developers to work with drives, folders & files.
➢ An introduction to the Visual
Basic Scripting Edition (VB
Script) some basic coding,
starting with file input and
output (i.e. reading and
writing to / from files).
➢ VBScript is a language that joins (or glues) the different components of Microsoft's scripting
technologies together. These components are comprised of automation objects (COM objects
Component Object Model) that expose different parts of an application to the developer.
➢ Automation objects are what make it possible for you to programmatically access the file
system and Create, Modify, Delete, Open, and Close files for different purposes.
VB Script 88
Nandha Arts and Science College PHP – II Unit BCA Department
Drive is an Object. Contains methods and properties that allow you to gather
Drive
information about a drive attached to the system
Drives is a Collection. It Provides a list of the drives attached to the system, either
Drives
physically or logically.
Files Files is a Collection. It Provides a list of all files contained within a folder.
Folders Folders is a Collection. It Provides a list of all the folders within a Folder.
TextStream TextStream is an Object. It enables developers to read and write text files.
Drive
Drive is an object, which provides access to the properties of a particular disk drive or network
share. The Following properties are supported by Drive object:
➢ AvailableSpace ➢ Path
➢ DriveLetter ➢ RootFolder
➢ DriveType ➢ SerialNumber
➢ FileSystem ➢ ShareName
➢ FreeSpace ➢ TotalSize
➢ IsReady ➢ VolumeName
VB Script 89
Nandha Arts and Science College PHP – II Unit BCA Department
Drives
Drives is a collection, which provides details of all the drives attached to the system, either
physically or logically. It carries two properties: Count Property, Item Property.
Example - 84
<html> <body>
<script language="vbscript" type="text/vbscript">
Dim oFS, d, dc, s, n
Set oFS = CreateObject("Scripting.FileSystemObject")
Set dc = oFS.Drives
C- Win 8.1::D-Personal ::
For Each d in dc
E-Common::F-Songs::5
n = ""
s = s & d.DriveLetter& " - "
If d.DriveType = 3 Then
n = d.ShareName
ElseIf d.IsReady Then
n = d.VolumeName
Else
n = "Drive not available"
End If
s = s & n & "::"
Next
document.write s
document.write dc.count
</script> </body> </html>
File
File is an Object, which contains both properties and methods that allow the developers to
create, delete or move a file.
Methods
• Open as Text Stream • Copy • Delete • Move
Properties
• Attributes • Drive • Name • Path
• Date Created • Parent Folder • Short Name • Short Path
• Date Last Accessed • Date Last Modified • Size • Type
VB Script 90
Nandha Arts and Science College PHP – II Unit BCA Department
Example – 85
<html> <body>
<script language="vbscript" type="text/vbscript">
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile("C:\user.vbs")
document.write "Line 1: "&f.DateCreated& "<br />"
document.write "Line 2: "&f.Attributes& "<br />"
document.write "Line 3: "&f.DateLastAccessed& "<br />"
document.write "Line 4: "&f.DateLastModified& "<br />"
document.write "Line 5: "&f.Drive& "<br />"
document.write "Line 6: "&f.Name& "<br />"
document.write "Line 7: "&f.ParentFolder& "<br />"
document.write "Line 8: "&f.Path& "<br />"
document.write "Line 9: "&f.ShortName& "<br />"
document.write "Line 10: "&f.ShortPath& "<br />"
document.write "Line 11: "&f.Size& "<br />"
document.write "Line 12: "&f.Type& "<br />"
f.copy ("D:\") & "<br />" 'copying to file to another location'
f.Move ("E:\") & "<br />" 'Move the file to another location'
f.Delete ("D:\") & "<br />" 'Delete to file from one location'
</script> </body> </html>
Files
Files is a collection, which provides a list of all files contained within a folder.
Properties • Count • Item
VB Script 91
Nandha Arts and Science College PHP – II Unit BCA Department
Example – 86
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim fso, f, f1, fc, s
Set oFS = CreateObject("Scripting.FileSystemObject")
'get the folder by giving its path
Set f = oFS.GetFolder("D:\PROJECT\")
Set fc = f.Files
'Get Item
Set s = fc.Item("sendmail.vbs")
'Get Count
x = fc.Count D:\PROJECT\sendmail.vbs
document.write s 6
document.write x
</script> </body>
</html>
Folder
Folder is an Object, which contains both properties and methods that allow the developers to
create, delete or move a folder.
Methods
• Copy • Delete • Move • Create Text
File Properties
➢ Attributes ➢ Drive ➢ Parent Folder ➢ Size
➢ Date Created ➢ Files ➢ Path ➢ Sub Folders
➢ Date Last Accessed ➢ Is Root Folder ➢ Short Name ➢ Type
➢ Date Last Modified ➢ Name ➢ Short Path
VB Script 92
Nandha Arts and Science College PHP – II Unit BCA Department
Example – 87
<html> <body>
<script language="vbscript" type="text/vbscript">
Dim fso, f, fc, nf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("D:\PROJECT")
Set fc = f.SubFolders
folderName = "Test_Folder"
If folderName <> "" Then
Set nf = fc.Add(folderName)
Else
Set nf = fc.Add("New Folder")
End If
</script> </body> </html>
TextStream
TextStream object helps the developers to work with text files seamlessly. Developers can read, write
or append the contents to the text file using the text stream object.
Syntax
TextStream.{property | method( )}
Example – 88
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTextFile
Set objTextFile = objFSO.CreateTextFile("D:\Testfile.txt")
objTextFile.Close
ConstForAppending = 8
Set objTextFile=objFSO.OpenTextFile("D:\Testfile.txt",ForAppending,True)
objTextFile.WriteLine "Welcome to VBScript Programming"
objTextFile.Close
Welcome to VBScript Programming
Set objTextFile = Nothing
Set objFSO = Nothing
</script> </body> </html>
VB Script 93
Nandha Arts and Science College PHP – II Unit BCA Department
Data Validation
➢ Data validation is the process of ensuring that a program
operates on Clean, Correct and Useful data. It use
routines often called “Validation rules” or “Check
routines”, that check for correctness, meaningfulness,
are security of data that are input to the system. The rules
may be implemented through the automated facilities of
a data dictionary, or by the inclusion of explicit application
program validation logic.
➢ Data validation is intended to provide certain well-
defined guarantees for fitness, accuracy, and consistency for any of various kinds of user input
into an applications or automated system.
➢ Data validation rules can be defined and designed using any of various methodologies, and be
deployed in any of various contexts. Set Datavalidation
➢ For business applications, data validation
can be defined through declarative data
integrity rules, or procedure-based
business rules. Data that does not conform
to these rules will negatively affect
business process execution. Therefore,
data validation should start with business
process definition and set of business rules
within this process. Rules can be collected through the requirements capture exercise.
➢ Data validation rules may be defined, designed and deployed.
Definition and design contexts:
✓ as a part of requirements-gathering phase in a software
engineering or designing a software specification
✓ as part of an operations modeling phase in business
process modeling
Deployment contexts:
✓ as part of a user-interface
✓ as a set of programs or business-logic routines in a programming language
✓ as a set of stored-procedures in a database management system
VB Script 94
Nandha Arts and Science College PHP – II Unit BCA Department
Validation methods
Allowed character checks: Checks that ascertain that only expected characters are present in a
field. For example a numeric field may only allow the digits 0-9, the
decimal point and perhaps a minus sign or commas. A text field such
as a < and >, an e-mail address might require at least one @ sign and
various other structural details.
Batch totals: Checks for missing records. Numerical fields may be added together
for all records in a batch. The batch total is entered and the computer
checks that the total is correct, e.g., add the 'Total Cost' field of a
number of transactions together.
Cardinality check: Checks that record has a valid number of related records. For
example if contact record in Payroll database is marked as "former
employee", then this record must not have any associated salary
payments after the date on which employee left organization.
Check digits: Used for numerical data. An extra digit is added to a number which is
calculated from the digits. The computer checks this calculation when
data are entered. For example the last digit of an ISBN for a book is a
check digit calculated modulus 10.
Consistency checks: Checks fields to ensure data in these fields corresponds, e.g., If Title
= "Mr.", then Gender = "M".
Control totals: This is a total done on one or more numeric fields which appears in
every record. This is a meaningful total, e.g., add the total payment
for a number of Customers.
Cross-system consistency checks: Compares data in different systems to ensure it is consistent, e.g.,the
address for the customer with the same id is the same in both
systems.
Data type checks: Checks the data type of the input and give an error message if the
input data does not match with the chosen data type, e.g., In an input
VB Script 95
Nandha Arts and Science College PHP – II Unit BCA Department
box accepting numeric data, if the letter 'O' was typed instead of the
number zero, an error message would appear.
File existence check: Checks that a file with a specified name exists. This check is essential
for programs that use file handling.
Format or picture check: Checks that the data is in a specified format (template), e.g., dates
have to be in the format DD/MM/YYYY. Regular expressions should
be considered for this type of validation.
Hash totals: This is just a batch total done on one or more numeric fields which
appears in every record. This is a meaningless total, e.g., add the
Telephone Numbers together for a number of Customers.
Limit check: Unlike range checks, data are checked for one limit only, upper OR
lower, e.g., data should not be greater than 2 (<=2).
Logic check: Checks that an input does not yield a logical error, e.g., an input value
should not be 0 when it will divide some other number somewhere in
a program.
Presence check: Checks that important data is actually present and have not been
missed out, e.g., customers may be required to have their telephone
numbers listed.
Range check: Checks that the data is within a specified range of values, e.g., the
month of a person's date of birth should lie between 1 and 12.
Referential integrity: In modern Relational database values in two tables can be linked
through foreign key and primary key.
Spelling and grammar check: Looks for spelling and grammatical errors.
Uniqueness check: Checks that each value is unique. This can be applied to several fields
(i.e. Address, First Name, and Last Name).
Table look up check: A table look up check takes the entered data item and compares it to
a valid list of entries that are stored in a database table.
VB Script 96
Nandha Arts and Science College PHP – II Unit BCA Department
Example – 89
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Validate
Dim TheForm
Set TheForm = Document.forms("ValidForm")
If IsNumeric(TheForm.Text1.Value) Then
If TheForm.Text1.Value < 1 Or TheForm.
Text1.Value > 10 Then
MsgBox "Please enter a number between 1& 10."
Else
MsgBox "Thank you."
End If
Else
MsgBox "Please enter a numeric value."
End If
End Sub
//-->
</SCRIPT> </HEAD>
<BODY>
<H3>Simple Validation</H3><HR>
<form id="ValidForm" action="nothing.asp" onsubmit="Validate();
return false;" language="jscript">
Enter a value between 1 and 10:
<input name="Text1" TYPE="TEXT" SIZE="2">
<input name="Submit" TYPE="Submit" VALUE="Submit">
</form> </BODY> </HTML>
Example – 90
<html> <head>
<title>VB Script Example</title>
<script language="”VBScript”">
Sub cmdSubmit_onClick
‘Check whether user has entered the required text or not.
VB Script 97
Nandha Arts and Science College PHP – II Unit BCA Department
If (Len(document.myform.txtage.value))) then
MsgBox “Please enter your age before submitting”
Exit Sub
End If
‘Check the data entered is numeric or not.
If (Not(IsNumeric(document.myform.txtage.value))) then
MsgBox “Please enter numeric data”
Exit Sub
End If
‘Check the range of the age
If (document.myform.txtage.value< 0) or (document.myform.txtage.value> 100) then
MsgBox “Age entered is Invalid”
Exit Sub
End If Please enter
‘If all is fine submit the data your age before
submitting
MsgBox “Thanks for providing your age”
document.myform.submit
End sub
</script> </head>
<body>
Please enter Age entered is
<form name="“myform”" id="“myform”"> numeric data Invalid
<table>
<tr>
<td>please enter your age:</td>
<td><input type="“text”" name="“txtage”" size="”2”"></td>
</tr>
<tr>
<td></td>
<td><input name="Submit" type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
VB Script 98
Nandha Arts and Science College PHP – II Unit BCA Department
• In the above example first we are checking whether the user has entered any value or not. If
he has not entered any value we will prompt to enter any value.
• Second validation is that if he has entered any value, just check whether the data entered is
numeric or not.
• If the next step we are validating that the age value is entered as per the prescribed range or
not. At last if all the validations are met by the user, he will be shown a message that “Thanks
for providing your age” and this data will be submitted to the web server.
Example – 91
<html> <head> <script language="VBScript">
<!-- Public Sub buttonHandler()
dim myVar
myVar = " ActiveX Control"
MsgBox myVar
End Sub ActiveX Control
VB Script 99
Nandha Arts and Science College PHP – II Unit BCA Department
ActiveX Scripting
You have already seen that web
browsers support a plain text syntax,
known as HTML, for displaying
information. HTML is a simple
language and, as such, provides few
mechanisms for extended interaction.
Some controls, such as buttons, are
supported basically; however, more
advanced user interface controls,
such as spinners, calendars, and grids, are not implemented.
In an effort to provide a completely interactive environment, Microsoft has introduced a standard for
including any scripting language within an HTML page. This standard is called ActiveX Scripting. ActiveX
Scripting is a language-independent standard that defines the relationship between a scripting host
and a scripting engine. A scripting engine is nothing more than an in-process ActiveX component,
formerly called an OLE server that conforms to the ActiveX Scripting specification. A scripting host is
an application that uses the scripting
engine. An example of a scripting host
is the Microsoft Internet Explorer 3.0.
ActiveX Scripting begins when an in-
process ActiveX component
representing the scripting engine is
instantiated inside the process space
VB Script 100
Nandha Arts and Science College PHP – II Unit BCA Department
of the Internet Explorer. After the scripting engine has been built by the Internet Explorer, it is loaded
with commands for execution. The commands themselves, called the script, live inside the actual
HTML page between the two tags <SCRIPT>and </SCRIPT>. After the script has been loaded into the
engine, the Internet Explorer runs the script through the engine. This action results in the functionality
defined by the commands in the code.
ActiveX Scripting.
Microsoft Visual Basic, Scripting Edition, is implemented with the scripting engine named vbscript.dll.
The VBScript engine and the Internet Explorer are not fundamentally joined therefore, vbscript.dll can
be used in any application that is an ActiveX scripting host. The VBScript engine understands the
VBScript language, which is nothing more than a subset of the existing Visual Basic for Applications
language. With the support of the Internet Explorer, VBScript can read and modify HTML form
elements, perform event handling, interact with the browser, and automate any ActiveX component.
---x---x---x---
VB Script 101
UNIT-III
JAVA SCRIPT
Form
HTML pages may include forms, which allow the user to fill out information and send it to the server.
A moderately complicated website can easily include anywhere from 10 to 200 resources. To be able
to fetch those quickly, browsers will make several requests simultaneously, rather than waiting for the
responses one at a time. Such documents are always fetched using GET requests.
Example – 92
<html>
<body>
<form method ="GET" action =" example/message.html">
<p>Name: <input type="text" name="name"></p>
<p>Message:<br><textarea name=" message"></textarea ></p>
<p><button type=" submit">Send </button ></p>
</form> </body> </html>
This code describes a form with two fields: a small one asking for a name and a larger one to write a
message in. When you click the Send button, the information in those fields will be encoded into a
query string
Fields
A web form consists of any number of input fields grouped in a <form> tag. HTML allows a number
of different styles of fields, ranging from simple on/off checkboxes to drop-down menus and fields
for text input. A lot of field types use the <input> tag. This tag’s type attribute is used to select the
field’s style. These are some commonly used <input> types:
text A single-line text field
password Same as text but hides the text that is typed
checkbox (Part of) a multiple-choice field
radio An on/off switch
file Allows the user to choose a file from their computer
Form fields do not necessarily have to appear in a <form> tag.
Nandha Arts and Science College PHP –III Unit BCA Department
Form Validation
What is Validation?
Validation means check the input submitted by the user. There are two types of validation are
available in PHP. They are as follows −
Client-Side Validation − Validation is performed on
the client machine web browsers.
Server Side Validation − After submitted by data, The
data has sent to a server and perform validation
checks in server machine.
JavaScript can be used to validate data in HTML forms
before sending off the content to a server.
Form data that typically are checked by a JavaScript
could be:
• Has the user left required fields empty?
• Has the user entered a valid e-mail address?
• Has the user entered a valid date?
• Has the user entered text in a numeric field?
Form validation normally used to occur at the
server, after the client had entered all the necessary data and then pressed the Submit button. If
the data entered by a client was incorrect or was simply missing, the server would have to send all
the data back to the client and request that the form be resubmitted with correct information. This
was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web
server. Form validation generally performs two functions.
Basic Validation -
First of all, the form must be checked to make sure all the mandatory fields are filled in. It
would require just a loop through each field in the form and check for data.
Data Format Validation -
Secondly, the data that is entered must be checked for correct form and value. Your code must
include appropriate logic to test correctness of data.
Example - 93
We will take an example to understand the process of
validation. Here is a simple form in html format.
<html>
<head>
<title> Form Validation</title>
<script language = “Javascript” type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script> </head>
<body>
<form action="contact.html" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr> <td align="right">Name</td>
<td> <input type="text" name="Name" /></td> </tr>
<tr> <td align="right"> EMail</td>
<td> <input type="text" name="EMail" /></td> </tr>
<tr> <td align="right">Zip Code</td>
<td> <input type="text" name="Zip" /></td> </tr>
<tr> <td align="right">Country</td>
<td> <select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option> </select> </td> </tr>
<tr> <td align="right"></td>
<td> <input type="submit" value="Submit" /></td> </tr>
</table> </form> </body> </html>
Basic Form Validation
First let us see how to do a basic form validation. In the above form, we are calling validate() to validate
data when on_Submit() event is occurring. The following code shows the implementation of this
validate() function.
Example - 94
<html> <head> <script>
function validateForm()
{
var x = document.forms["myForm"]["fname"].value;
if (x == "")
{
alert("Name must be filled out");
return false;
}
}
</script> </head> <body>
<form name="myForm" action="/action_page_post.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form> </body> </html>
(OR)
Example - 94
<script language = “Javascript” type="text/javascript">
<!—
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Required Fields:
The function below checks if the field has been left empty. If the field is blank, an alert box
alerts a message, the function returns false, and the form will not be submitted.
E-mail Validation:
The function below checks if the content has the general syntax of Valid
Example - 95
function validateForm()
{
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1|| dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
JavaScript SSI and Cookies:
What is a Cookie?
A cookie is an amount of information that persists between a server-side and a client-side. A web
browser stores this information at the time of browsing. A cookie contains the information as a string
generally in the form of a name-value pair separated by semi-colons. It maintains the state of a user
and remembers the user's information among all the web pages.
A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user's
computer. They are typically used to keeping track of information such as username that the site can
retrieve to personalize the page when user visit the website next time.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object, which
looks like this.
document.cookie = "key1=value1; key2=value2; expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time,
then the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when you
read the cookie value.
Example – 96
<html> <head> <script language = “Javascript” type="text/javascript">
<!--
function WriteCookie()
{
if ( document.myform.customer.value == "" ) {
alert ("Enter some value!");
return;
}
Now your machine has a cookie called name. You can set multiple cookies using multiple key=value
pairs separated by comma.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is
the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons, where
name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows:
Example - 97
<html>
<head>
<script language = “Javascript” type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++)
Java Script 109
Nandha Arts and Science College PHP –III Unit BCA Department
{
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script> </head> <body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form> </body>
</html>
Note: Here length is a method of Array class
which returns the length of an array.
Note: The above code will display all the cookies set on your machine.
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return
nothing. To do this, you just need to set the expiry date to a time in the past.
Example – 99 it illustrates how to delete a cookie by setting its expiry date to one month behind the current date.
be configured to allow SSIs to run. The most popular web server is currently Apache which, as
a development of the WWW server, can be seen as the server for which SSIs were created.
If your server is already configured for them, SSIs are incredibly(very) simple to use. For
example, to include the same code for a navigation bar on every page in your site, save the
required code in a plain text file - just the code, no <html>, <head> or <body>
tags (unless they are part of the code to be included) - and call it anything.
SSI-enabled servers recognize which pages which require parsing by their filename extension.
SSIs can be a powerful tool for site management and are especially useful for the maintenance
of sites which require frequent changes. They are also particularly valuable when you are
weaning yourself off using frames.
SSI includes, there are six built-in objects. They are,
1. Server object. 2. Project object. 3. Client object.
4. Request object. 5. File object. 6. Database object.
Disadvantages of Frames
There are few drawbacks with using frames, so it's never recommended to use frames in your webpages:
▪ Some smaller devices cannot cope with frames often because their screen is not big enough
to be divided up.
▪ Sometimes your page will be displayed differently on different computers due to different
screen resolution.
▪ The browser's back button might not work as the user hopes.
▪ There are still few browsers that do not support frame technology.
Creating Frames
To use frames on a page we use <frameset> tag instead of <body> tag. The <frameset> tag defines,
how to divide the window into frames. The rows attribute of <frameset> tag defines horizontal frames
and cols attribute defines vertical frames. Each frame is indicated by <frame> tag and it defines which
HTML document shall open into the frame.
Example 101 :- Let's put the above example as follows, here we replaced rows attribute by
cols and changed their width. This will create all the three frames vertically:
<html>
<head> <title>HTML Frames</title> </head>
<frameset cols="25%,50%,25%">
<frame name="left" src="/html/top_frame.htm" />
<frame name="center" src="/html/main_frame.htm" />
<frame name="right" src="/html/bottom_frame.htm" />
<noframes>
<body> Your browser does not support frames.
</body> </noframes> </frameset> </html>
rows This attribute works just like the cols attribute and takes the same values, but it is used to specify the
rows in the frameset. For example, to create two horizontal frames, use rows="10%, 90%". You can
specify the height of each row in the same way as explained above for columns.
border This attribute specifies the width of the border of each frame in pixels. For example, border="5". A
value of zero means no border.
Frame This attribute specifies whether a three-dimensional border should be displayed between frames.
border This attribute takes value either 1 (yes) or 0 (no). For example frameborder="0" specifies no border.
Frame This attribute specifies the amount of space between frames in a frameset. This can take any integer
spacing value. For example framespacing="10" means there should be 10 pixels spacing between each frames.
The <frame> Tag Attributes Following are the important attributes of <frame> tag:
Attribute Description
src This attribute is used to give the file name that should be loaded in the frame. Its value can be any
URL. For example, src="/html/top_frame.htm" will load an HTML file available in html directory.
This attribute allows you to give a name to a frame. It is used to indicate which frame a document
name should be loaded into. This is especially important when you want to create links in one frame that
load pages into an another frame, in which case the second frame needs a name to identify itself as
the target of the link.
This attribute specifies whether or not the borders of that frame are shown; it overrides the value
Frame
given in the frameborder attribute on the <frameset> tag if one is given, and this can take values
border either 1 (yes) or 0 (no).
Margin This attribute allows you to specify the width of the space between the left and right of the frame's
width borders and the frame's content. The value is given in pixels. For example marginwidth="10".
Margin This attribute allows you to specify the height of the space between the top and bottom of the frame's
height borders and its contents. The value is given in pixels. For example marginheight="10".
noresize By default, you can resize any frame by clicking and dragging on the borders of a frame. The noresize
attribute prevents a user from being able to resize the frame. For example noresize="noresize".
scrolling This attribute controls the appearance of the scrollbars that appear on the frame. This takes values
either "yes", "no" or "auto". For example scrolling="no" means it should not have scroll bars.
longdesc This attribute allows you to provide a link to another page containing a long description of the
contents of the frame. For example longdesc= "framedescription.htm"
Example – 102 Let's see following example where a test.htm file has following code:
<html>
<head>
<title>HTML Target Frames</title>
</head>
<frameset cols="200, *">
<frame src="/html/menu.htm" name="menu_page" />
<frame src="/html/main.htm" name="main_page" />
<noframes>
<body>
Your browser does not support frames.
</body> </noframes>
</frameset> </html>
Here, we have created two columns to fill with two frames. The first frame is 200 pixels wide and will
contain the navigation menu bar implemented by menu.htm file. The second column fills in
remaining space and will contain the main part of the page and it is implemented by main.htm file.
For all the three links available in menu bar, we have mentioned target frame as main_page, so
whenever you click any of the links in menu bar, available link will open in main page.
Now you can try to click links available in the left panel and see the result. The target
attribute can also take one of the following values:
Option Description
_self Loads the page into the current frame.
Loads the page into the parent window, which in the case of a single frameset
_parent
is the main browser window.
_top Loads the page into the browser window, replacing any current frames.
targetframe Loads the page into a named targetframe.
MIME Types:
Multipurpose Internet Mail Extensions, a specification for formatting non-ASCII messages so
that they can be sent over the Internet. Many e-mail clients now support MIME, which enables
them to send and receive graphics, audio, and video files via the Internet mail system. In
addition, MIME supports messages in character sets other than ASCII.
There are many predefined MIME types, such as GIF graphics files and PostScript files.
It is also possible to define your own MIME types.
In addition to e-mail applications, Web browsers also support various MIME types.
This enables the browser to display or output files that are not in HTML format.
MIME was defined in 1992 by the Internet Engineering Task Force (IETF). A new
version, called S/MIME, supports encrypted messages.
What is a Content-Type?
A "Content-type" is simply a header defined in
many protocols, such as HTTP, that makes use of
MIME types to specify the nature of the file
currently being handled.
Through the use of the multipart type, MIME
allows mail messages to have parts arranged in a
tree structure where the leaf nodes are any non-
multipart content type and the non-leaf nodes
are any of a variety of multipart types. This
mechanism supports:
Simple text messages using text/plain (the default value for "Content-Type: ")
Text plus attachments (multipart/mixed with a text/plain part and other non-text parts). A MIME
message including an attached file generally indicates the file's original name with the "Content-
disposition:" header, so the type of file is indicated both by the MIME content-type and the (usually OS-
specific) filename extension
Reply with original attached (multipart/mixed with a text/plain part and the original message).
Alternative content, such as a message sent in both plain text and another format such as
HTML (multipart/alternative with the same content in text/plain and text/html forms)
Image, audio, video and application (for example, image/jpeg, audio/mp3, video/mp4, and
application/MS Word and so on)
JavaScript: Plug-ins:
In computing, a plug-in (or plugin, add-in, addin, add-on, or addon) is a software component
that adds a specific feature to an existing computer program. When a program supports plug-
ins, it enables customization.
A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By
extending the prototype object you enable all jQuery objects to inherit any methods that you
add. As established, whenever you call jQuery() you're creating a new jQuery object, with all
of jQuery's methods inherited.
The idea of a plugin is to do something with a collection of elements. You could consider each
method that comes with the jQuery core a plugin, like .fadeOut() or .fadeIn ().
A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery
methods which can be used along with jQuery library methods.
<head>
<title> The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src = "jquery.plug-in.js" type = "text/javascript"> </script>
<script src = "custom.js" type = "text/javascript"> </script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function()
{
.......your custom code.....
});
</script>
</head>
<body>
.............................
</body> </html>
What is jQuery?
JavaScript and jQuery are actually the same thing. In a nutshell, jQuery is a set of JavaScript libraries that
have been designed specifically to simplify HTML document traversing, animation, event handling, and Ajax
interactions. Before jQuery was developed, web developers created their own custom frameworks in
JavaScript. This allowed them to work around specific bugs without wasting time debugging common features.
This led to groups of developers creating JavaScript libraries that were open source and free to use.
What is Framework?
A JavaScript framework is an application framework written in JavaScript. It differs from a JavaScript library
in its control flow: a library offers functions to be called by its parent code, whereas a framework defines the
entire application design. A developer does not call a framework; instead it is the framework that will call and
use the code in some particular way. Some JavaScript frameworks follow the model–view–controller paradigm
designed to segregate a web application into orthogonal units to improve code quality and maintainability.
Examples: AngularJS, Ember.js, Meteor.js.
What is AJAX?
AJAX = Asynchronous JavaScript and XML. It is a technique for creating fast and dynamic web pages. It
allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind
the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications: Google Maps, Gmail, Youtube, and Facebook tabs.
---x---x---x---
PHP Syntax(Basic):
A PHP script can be placed anywhere in the document.
A PHP script starts with
<?php // PHP code goes here ?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:
Example – 105
<html>
My First PHP
<body>
<h1> My first PHP page</h1>
page
<?php Hello World
echo "Hello World!";
?>
</body>
</html>
Note: PHP statements are terminated by semicolon (;).
The closing tag of a block of PHP code also automatically implies a semicolon.
Example – 106
Echo Example Program
<html> Hello by PHP echo this is multi line text printed by PHP echo statement
<body>
<h1> Echo Example Program </h1>
<?php
echo "Hello by PHP echo
this is multi line
text printed by
Echo Example Program
Message is:
PHP echo statement
Hello! I am Learn in PHP Language
";
?> </body> </html>
Example – 107
<html> <body> <h2> Echo Example Program </h1>
<?php
$msg="Hello! I am Learn in PHP Language";
echo "Message is: $msg";
?> </body> </html>
Comments in PHP:
A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose
is to be read by someone who is editing the code!
Comments let other programmers understand what you were doing in each step
To remind yourself what you did - Most programmers have experienced coming back to their own
work a year or two later and having to re-figure out what they did.
Comments can remind you of what you were thinking when you wrote the code.
PHP supports three ways of commenting.
Example – 108
<html> <body>
<?php // This is a single line comment # This is also a single line comment
/*This is a multiple lines comment block that spans over more than one line */
?> </body> </html>
PHP Case Sensitivity:
▪ In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are case-insensitive.
▪ In the example below, all three echo statements below are legal (and equal):
Example – 109
Hello World!
<html> <body> Programmer
follow in this Hello World!
<?php
method only
Hello World!
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?> </body> </html>
PHP Variables:
Variables are "containers" for storing information
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Variables in PHP do not have intrinsic (basic) types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
PHP has a total of eight data types which we use to construct our variables:
Integers: are whole numbers, without a decimal point, like 4195.
Doubles: are floating-point numbers, like 3.14159 or 49.1.
Booleans: have only two possible values either true or false.
NULL: is a special type that only has one value: NULL.
Strings: are sequences of characters, like 'PHP supports string operations.'
Arrays: are named and indexed collections of other values.
Objects: are instances of programmer-defined classes, which can package up both other kinds
of values and functions that are specific to the class.
Resources: are special variables that hold references to resources external to PHP
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type.
<?php
$a="hello"; //letter (valid)
hello
$_b="hello"; //underscore (valid) hello
echo "$a <br/> $_b";
?>
Example – 110
<?php Much like Algebra
$x=5; x = 5 11
$y=6; (or) y = 6
$z=$x+$y; z = x+y
echo $z;
?>
Example – 111
<?php
$txt="Hello world!";
$x=5;
$y=10.5;
?>
PHP is a Loosely Type Language:
PHP automatically converts the variable to the correct data type, depending on its value.
In other languages such as C, C++, and Java, the programmer must declare the name and
type of the variable before using it.
PHP Variables Scope:
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
-> Local -> Global -> Static -> Function parameters
Local Variables
A variable declared in a function is considered local; that is, it can be referenced only in that function.
Example – 112
$x inside function is 0.
<?
$x outside of function is 4.
$x = 4;
function assign x ()
{
$x = 0;
print "\$x inside function is
$x. ";
}
assignx();
print "\$x outside of function is $x. ";
?>
Global Variables
In contrast to local variables, a global variable can be accessed in any part of the program. However,
in order to be modified, a global variable must be explicitly declared to be global in the function in
which it is to be modified. This is accomplished, conveniently enough, by placing the keyword
GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of
an already existing variable tells PHP to use the variable having that name. Consider an example:
Example – 113
Somevar is 16
<?
$somevar = 15;
function addit()
{
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
} Test variables inside the function:
addit();
E_NOTICE : type 8 -- Undefined variable: x -- at line 8
?> Variable x is:
Variable y is: 10
Example – 114
Test variables outside the function:
<?php
Variable x is: 5
$x=5; Variable y is: 5
$y=5; // global scope
function myTest()
{
$y=10; // local scope
echo "<p>Test variables inside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
}
myTest();
echo "<p>Test variables outside the function:<p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y"; ?>
Example – 115
<?php
$x=5;
$y=10;
function myTest()
{ Output
global $x,$y; 15
$y=$x+$y;
}
myTest();
echo $y;
?>
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.
Example – 116
<?php Output
$x=5;
$y=20; 25
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;
?>
PHP 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:
▪ The variables declared as function parameters, which are destroyed on the function's exit, a
static variable will not lose its value when the function exits and will still hold that value should
the function be called again.
▪ You can declare a variable to be static simply by placing the keyword static in front of the
variable name.
Example – 117
<?php
function myTest()
{
static $x=0; Output
echo $x;
$x++; 0
} 1
myTest(); 3
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it.
Note: The variable is still local to the function.
Example – 120 (Display different String Variable with the echo command)
<?php PHP is fun
print "<h2>PHP is fun!</h2>";
Hello world
print "Hello world!<br>";
print "I'm about to learn PHP!"; I’m about to learn PHP
?>
Example – 122
<?php
Hello world!
$x = "Hello world!";
echo $x; Hello Friends!
echo "<br>";
$x = 'Hello Friends!';
echo $x;
?>
PHP Integers
An integer is a number without decimals.
Rules for integers:
• An integer must have at least one digit (0-9)
• An integer cannot contain comma or blanks
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based), hexadecimal (16- based -
prefixed with 0x) or octal (8-based - prefixed with 0)
The PHP var_dump() function returns the data type and value of variables:
Example – 123
<?php $x = 5985;
int(5985)
var_dump($x); int(-345)
echo "<br>"; int(140)
$x = -345; // negative number
var_dump($x);
echo "<br>";
$x = 0x8C; // hexadecimal number
“var_dump” function, which limits the
var_dump($x);
output and prints the file path and line
echo "<br>";
of the invocation.
$x = 047; // octal number var_dump($x);
?>
Example – 124
<?php $x = 10.365;
var_dump($x); echo "<br>";
$x = 2.4e3; float(10.365)
var_dump($x); echo "<br>"; float(2400)
$x = 8E-5; float(8.0E-5)
var_dump($x);
?>
PHP Booleans
Booleans can be either TRUE or FALSE.
$x=true; $y=false;
Booleans are often used in conditional testing.
PHP NULL Value
• The special NULL value represents that a variable has no value. NULL is the only possible
value of data type NULL.
• The NULL value identifies whether a variable is empty or not. Also useful to differentiate
between the empty string and null values of databases.
• Variables can be emptied by setting the value to NULL:
Example – 125
<?php
$x="Hello world!";
$x=null; null
var_dump($x);
?>
PHP Constants:
Constants are like variables except that once they are defined they cannot be changed or undefined.
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 define a constant you have to use define() function and to retrieve the value of a constant, you have
to simply specifying its name. Unlike with variables, you do not need to have a constant with a $. You can
also use the function constant() to read a constant's value if you wish to obtain the constant's name
dynamically.
Note: Unlike variables, constants are automatically global across the entire script.
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e.,
it is stored in a variable or returned by a function.
Example – 126
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line 5050
?>
Only scalar data (boolean, integer, float and string) can be contained in
constants.
Example – 127
<?php
Welcome to
define("GREETING", "Welcome to RajHotel.com!"); RajHotel.com!
echo GREETING;
?>
Expressions:
In PHP there are two types of expression for us to look at. One is something called a "regular
expression", which is used in the manipulation of text. The other is more mathematical in
nature, expressing operations to be performed on values and variables. Here's a simple
example: c = a + b
Assuming a and b are numbers (remember data types? -- the result would be different if
they were strings -- more about that later) this expression would add a and b and put the
sum into c. In the expression a + b the plus sign is an arithmetic operator.
Expressions are the most important building stones of PHP. In PHP, almost anything you write
is an expression. The simplest yet most accurate way to define an expression is "anything
that has a value".
The most basic forms of expressions are constants and variables. When you type "$a = 5",
you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an
expression with the value of 5 (in this case, '5' is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd
expect it to behave just as if you wrote $b = 5.
In other words, $a is an expression with the value of 5 as well. If everything works right, this
is exactly what will happen.
Example – 128
<?php
function foo()
{
return 5;
}
?>
PHP Operators:
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5
are called operands and + is called operator. PHP language supports following type of operators.
• Arithmetic Operators • Comparison Operators
• Logical (or Relational) Operators • Assignment Operators
• Conditional (or Ternary) Operators
Example – 129
<html>
<head>
<title>Arithmetical Operators</title>
</head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b;
echo "Addition Operation Result: $c <br/>";
$c = $a - $b;
echo "Subtraction Operation Result: $c <br/>";
$c = $a * $b;
echo "Multiplication Operation Result: $c <br/>";
$c = $a / $b;
echo "Division Operation Result: $c <br/>";
$c = $a % $b;
echo "Modulus Operation Result: $c <br/>";
$c = $a++;
echo "Increment Operation Result: $c <br/>";
$c = $a--;
echo "Decrement Operation Result: $c <br/>";
?>
</body>
</html>
}
if( $a >= $b ){
echo "TEST5 : a is either greater than or equal to b<br/>";
}else{
echo "TEST5 : a is neither greater than nor equal to b<br/>";
}
if( $a <= $b ){
echo "TEST6 : a is either less than or equal to b<br/>";
}else{
echo "TEST6 : a is neither less than nor equal to b<br/>";
}
?>
</body>
</html>
Logical Operators
The following logical operators are supported by PHP language.
Assume variable A holds 10 and variable B holds 20 then:
&& Called Logical AND operator. If both the operands are non zero, (A && B) is true.
then condition becomes true.
|| Called Logical OR Operator. If any of the two operands are non (A || B) is true.
zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of !(A && B) is false.
its operand. If a condition is true, then Logical NOT operator will
make false.
Example – 131
<html>
<head><title>Logical Operators</title></head>
<body>
<?php
$a = 42;
$b = 0;
if( $a && $b ) {
echo "TEST1 : Both a and b are true<br/>";
} else{
echo "TEST1 : Either a or b is false<br/>";
}if( $a and $b ){
echo "TEST2 : Both a and b are true<br/>";
}else{
echo "TEST2 : Either a or b is false<br/>";
} if( $a || $b ){
echo "TEST3 : Either a or b is true<br/>";
}else{
echo "TEST3 : Both a and b are false<br/>";
}if( $a or $b ){
echo "TEST4 : Either a or b is true<br/>";
}else{
echo "TEST4 : Both a and b are false<br/>";
}
$a = 10; $b = 20;
if( $a ){
echo "TEST5 : a is true <br/>";
}else{
TEST1 : Either a or b is false
echo "TEST5 : a is false<br/>"; TEST2 : Either a or b is false
TEST3 : Either a or b is true
}if( $b ){
TEST4 : Either a or b is true
echo "TEST6 : b is true <br/>"; TEST5 : a is true
}else{ TEST6 : b is true
TEST7 : a is false
echo "TEST6 : b is false<br/>";
TEST8 : b is false
}if( !$a ){
echo "TEST7 : a is true <br/>";
}else{
echo "TEST7 : a is false<br/>";
}if( !$b ){
echo "TEST8 : b is true <br/>";
}else{
echo "TEST8 : b is false<br/>";
}
?> </body> </html>
= Simple assignment operator, Assigns values from right side operands to left C = A + B will assign the value of A + B
side operand into C
+= Add AND assignment operator, It adds right operand to the left operand and C += A is equivalent to
assign the result to left operand
-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is equivalent to C=C-A
operand and assign the result to left operand
*= Multiply AND assignment operator, It multiplies right operand with the left C *= A is equivalent to C = C*A
operand and assign the result to left operand
/= Divide AND assignment operator, It divides left operand with the right operand C /= A is equivalent to C= C / A
and assign the result to left operand
%= Modulus AND assignment operator, It takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand
Example – 132
<html> <head><title>Assignment Operators</title></head>
<body> <?php
$a = 42; $b = 20;
$c = $a + $b; /* Assignment operator */
echo "Addition Operation Result: $c <br/>";
$c += $a; /* c value was 42 + 20 = 62 */
echo "Add AND Assignment Operation Result: $c <br/>";
$c -= $a; /* c value was 42 + 20 + 42 = 104 */
echo "Subtract AND Assignment Operation Result: $c <br/>";
$c *= $a; /* c value was 104 - 42 = 62 */
echo "Multiply AND Assignment Operation Result: $c <br/>";
$c /= $a; /* c value was 62 * 42 = 2604 */
echo "Division AND Assignment Operation Result: $c <br/>";
$c %= $a; /* c value was 2604/42 = 62*/
echo "Modulus AND Assignment Operation Result: $c <br/>";
?> </body> </html>
Conditional Operator
There is one more operator called the conditional operator. It first evaluates an expression for a true
or false value and then executes one of the two given statements depending upon the result of
the evaluation.
Example – 133
<html>
<head><title>Arithmetical Operators</title><head>
<body>
TEST1 : Value of result is 20
<?php
TEST2 : Value of result is 10
$a = 10;
$b = 20;
/* If condition is true then assign a to result otherwise b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otherwise b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?> </body> </html>
Operators Categories
All the operators we have discussed above can be categorized into the following categories:
• Unary prefix operators, which precede a single operand.
• Binary operators, which take two operands and perform a variety of arithmetic and logical
operations.
• The conditional operator (a ternary operator), which takes three operands and evaluates
either the second or third expression, depending on the evaluation of the first expression.
• Assignment operators, which assign a value to a variable.
Example – 134
<?php
$a = "Hello";
$b = $a."world!";
Helloworld! Helloworld!
echo $b;
$x="Hello";
$x.="world!";
echo $x;
?>
If Statement
An if statement is a way of controlling the execution of a statement that follows it (that is, a
single statement or a block of code inside braces).
The if statement evaluates an expression between parentheses. If this expression results in a
true value, the statement is executed.
Otherwise, the statement is skipped entirely. This enables scripts to make decisions based on
any number of factors:
Syntax:-
if ( expression )
{
Statement; or code to be executed if condition is true;
}
Example – 135 The following code would display a is bigger than b if $a is bigger than $b:
<?php
$a=10; $b=5;
if ($a > $b) A is bigger than B
{
echo "A is bigger than B";
} ?>
Else Statement:
• When working with the if statement, you will often want to define an alternative block of code
that should be executed if the expression you are testing evaluates to false.
• You can do this by adding else to the if statement followed by a further block of code:
Syntax:-
if ( expression ) if (condition)
{
Statement; code to be executed if condition is true;
} (Or)
else else
{
code to be executed if condition is false;
Statement;
}
Example – 136 the following code would
display a is bigger than b if $a is bigger than $b, and a is NOT bigger than b otherwise:
<?php
$a=10; $b=15;
if ($a > $b) {
echo "A is bigger than B"; B is bigger than A
}
else {
echo "B is bigger than A";
} ?>
If..Else..if Statement (or) Nested if Statement
As its name suggests, is a combination of if and else. Like else, it extends an if statement to
execute a different statement in case the original if expression evaluates to FALSE.
However, unlike else, it will execute that alternative expression only if the elseif conditional
expression evaluates to TRUE.
Syntax:-
if ( expression )
{
Statement; if (condition)
}
code to be executed if condition is true;
elseif
{ Or elseif (condition)
Statement;
} code to be executed if condition is true;
else
{ else
Statement
} code to be executed if condition is false;
Example – 137
<?php $a=10; $b=10;
if ($a > $b){ A and B are equal
echo "A is bigger than B"; }
elseif ($b > $a) {
echo " B is bigger than A "; }
else {
echo "A and B are equal";
} ?>
Switch Statement:
The switch statement is similar to a series of IF statements on the same expression.
In many occasions, you may want to compare the same variable (or expression) with many
different values, and execute a different piece of code depending on which value it equals to.
Syntax:-
switch (expression)
{
case label 1:
code to be executed if expression = label1;
break;
case label 2:
code to be executed if expression = label2;
break;
default:
code to be executed
}
Example – 138
<html>
<body>
<?php
$d=date("D"); Today is Sunday
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
} ?> </body> </html>
PHP Loops:
Loops in PHP are used to execute the same block of code a specified number of times.
In PHP, we have the following looping statements:
for - loops through a block of code a specified number of times.
while - loops through a block of code if and as long as a specified condition is true.
do...while - loops through a block of code once, and then repeats the loop as long as a special
condition is true.
foreach - loops through a block of code for each element in an array.
Example – 139
<?php
The number is: 1
$x=1; The number is: 2
while($x<=5) The number is: 3
{ The number is: 4
The number is: 5
echo "The number is: $x <br>";
$x++;
}
?>
Example – 140
<?php
$x=1;
do
The number is: 1
{
The number is: 2
echo "The number is: $x <br>"; The number is: 3
$x++; The number is: 4
The number is: 5
}
while ($x<=5)
?>
Example – 142
Value is 1
<html>
Value is 2
<body> Value is 3
<?php Value is 4
Value is 5
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
Example – 143
<html>
<body>
<?php
$array = array( 'A','B','C','D','E'); Value is A
Value is B
foreach( $array as $value )
Value is C
{ Value is D
echo "Value is $value <br />"; Value is E
}
?>
</body>
</html>
Example – 145
<html> <body> <?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
Value is 1
{ Value is 2
Value is 4
if( $value == 3 )
Value is 5
continue;
echo "Value is $value <br />";
}
?> </body> </html>
Array
An array is a data structure that stores one or more similar type of values in a single value. For
example, if you want to store 100 numbers, then instead of defining 100 variables, it is easy to define
an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID which is called
array index.
1. Numeric array or Indexed array - An array with a numeric index. Values are stored and accessed
in linear fashion.
2. Associative array - An array with strings as index. This store element values in association with
key values rather than in a strict linear index order.
3. Multidimensional array - An array containing one or more arrays and values are accessed using
multiple indices NOTE: Built-in array functions is given in function reference PHP Array Functions
There are two ways to define Numeric or indexed array:
1st way: $season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter"; Season are: summer,
$season[2]="spring"; winter, spring, autumn
$season[3]="autumn";
Example – 146
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Example – 147
<?php Season are: summer,
$season[0]="summer"; winter, spring and
$season[1]="winter"; autumn
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by numbers.
By default, the array index starts from zero.
Example – 148
<html>
<body>
<?php
/* First method to create array. */
Value is 1
$numbers = array( 1, 2, 3, 4, 5); Value is 2
Value is 3
foreach( $numbers as $value ) Value is 4
Value is 5
{ Value is one
Value is two
echo "Value is $value <br />"; Value is three
Value is four
} Value is five
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?> </body> </html>
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are different
in terms of their index. Associative array will have their index as string so that you can establish a
strong association between key and values. To store the salaries of employees in an array, a
numerically indexed array would not be the best choice. Instead, we could use the employees names
as the keys in our associative array, and the value would be their respective salary.
We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sumathi"=>"350000","Raja"=>"450000","Karthik"=>"600000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example – 149
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("Raja"=>50000,"Sumathi"=>35000,"Banu"=>25000);
echo "Salary of Raja is ".$salaries['Raja']. "<br />";
echo "Salary of Sumathi is ".$salaries['Sumathi']. "<br />";
echo "Salary of Banu is ".$salaries['Banu']. "<br />";
/* Second method to create array. */
$salaries['Raja'] = "high";
Salary of Raja is 50000
$salaries['Sumathi'] = "medium"; Salary of Sumathi is 35000
$salaries['Banu'] = "low"; Salary of Banu is 25000
echo "Salary of Raja is Salary of Raja is high
Salary of Sumathi is medium
".$salaries['Raja']. "<br />";
Salary of Banu is low
echo "Salary of Sumathi is
".$salaries['Sumathi']. "<br />";
echo "Salary of Banu is ".$salaries['Banu']. "<br />";
?>
</body>
</html>
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each element in
the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using
multiple index.
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an
array. PHP multidimensional array can be represented in the form of matrix which is represented by
row * column.
Definition
$emp = array
(
array(1,"sumathi",400000),
array(2,"raja",500000),
array(3,"rahul",300000)
);
Example – 150 Create a two-dimensional array to store marks of three students in three subjects:
<html>
<body>
<?php
$marks = array(
"Raja" => array ("physics" => 95, "maths" => 90, "chemistry" => 89),
"Sumathi" => array ( "physics" => 30, "maths" => 92, "chemistry" => 29),
"Banu" => array("physics" => 31, "maths" => 22, "chemistry" => 89 ) );
/* Accessing multi-dimensional array values */
echo "Marks for Raja in physics : " ;
echo $marks['Raja']['physics'] . "<br />";
echo "Marks for Sumathi in maths : ";
echo $marks['Sumathi']['maths'] . "<br />";
echo "Marks for Banu in chemistry : " ;
echo $marks['Banu']['chemistry'] . "<br />";
?>
</body>
</html> Marks for Raja in physics : 95
Marks for Sumathi in maths : 92
Marks for Banu in chemistry : 89
---x---x---x---
Creating a Function
While creating a user defined function we need to keep few things in mind:
Any name ending with an open and closed parenthesis is a function.
A function name always begins with the keyword function.
To call a function we just need to write its name followed by the parenthesis
A function name cannot start with a number. It can start with an alphabet or underscore.
A function name is not case-sensitive.
You can pass values to functions, which will then work with them. When finished, a function
can pass a value back to the calling code.
1. Creating PHP Functions 3. Calling PHP Functions
2. Use Parameters - Functions 4. Returning Values - Functions Creating PHP Functions:
Syntax:
function function_name()
{
executable code;
}
Example – 152
<?php
function bighello($firstName)
{ Raj
echo "Hello ". $firstName . "!";
}
bighello('Raj');
?>
Example – 153
<html> <head>
<title> Writing PHP Function with Parameters</title> </head>
<body> <?php
Sum of the two numbers
function addfunction($num1, $num2) is : 30
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addfunction(10, 20);
?> </body> </html>
Example – 155
<html>
<head>
<title> Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) Returned value from the
{
function : 50
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(25, 25);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
Setting Default Values for Function Parameters
You can set a parameter to have a default value if the function's caller doesn't pass it. The following
function prints NULL in case use does not pass any value to this function.
Example – 156
<html>
<head>
<title> Writing PHP Function which returns value</title>
</head>
<body>
<?php
This is test
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
Example – 158
<?php
class Books
{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par)
{
$this->price = $par;
}
function getPrice()
{
echo $this->price ."<br/>";
}
function setTitle($par)
{
$this->title = $par;
}
function getTitle()
{
echo $this->title ." <br/>";
}
}
?> The variable $ this is a special variable and it refers to the same object, i.e., itself.
Define Object
An Object is an individual instance of the data structure defined by a class. We define a class once and
then make many objects that belong to it. Objects are also known as instances. Once you defined your
class, then you can create as many objects as you like of that class type.
class Book
{
// Members of class Book
}
// Creating three objects of book
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Calling Member Functions
After creating your objects, you will be able to call member functions related to that object. One
member function will be able to process member variable of related object only. Following example
shows how to set title and prices for the three books by calling member functions.
Example – 159
<?php
class Mobile
{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par)
{
$this->price = $par;
}
function getPrice()
{
echo $this->price ."<br/>";
}
function setName($par)
{
$this->title = $par;
}
function getName()
{
echo $this->title ." <br/>";
}
}
$Samsung = new Mobile();
$Xiaomi = new Mobile();
$Iphone = new Mobile();
$Samsung->setName( "SamsungS8 );
$Iphone->setName( "Iphone7s" );
$Xiaomi->setName( "MI4" );
$Samsung->setPrice( 90000 ); Samsung S8
$Iphone->setPrice( 95000 ); Iphone S7
$Xiaomi->setPrice( 15000 ); MI4
$Samsung->getName();
90000
$Iphone->getName();
95000
$Xiaomi->getName();
$Samsung->getPrice(); 15000
$Iphone->getPrice();
$Xiaomi->getPrice();
?>
Public Members
Unless you specify otherwise, properties and methods of a class are public. That is to say, they may
be accessed in three possible situations:
• From outside the class in which it is declared
• From within the class in which it is declared
• From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the
members of a class, then you define class members as private or protected.
Example – 160
<?php
// Define MyClass
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
//Define MyClass2
class MyClass2 extends MyClass
{
// We can redeclare the public and protected properties, but not private
public $public = 'Public2';
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
Private members
By designating a member private, you limit its accessibility to the class in which it is declared. The
private member cannot be referred to from classes that inherit the class in which it is declared and
cannot be accessed from outside the class. A class member can be made private by using private
keyword in front of the member.
Protected members
A protected property or method is accessible in the class in which it is declared, as well as in classes
that extend that class. Protected members are not available outside of those two kinds of classes. A
class member can be made protected by using protected keyword in front of the member.
Inheritance
When the properties and the methods of the parent class are accessed by the child class, we call the
concept has inheritance. The child class can inherit the parent method and give own method
implementation, this property is called overridden method. When the same method of the parent
class is inherited we call as inherited method. Now let us see types of inheritance supported in Object
Oriented Programming and corresponding Php inheritance examples.
Types of Inheritance
1. Single Level Inheritance 2. Multilevel Inheritance
1. Single Level Inheritance: In Single Level Inheritance the Parent class methods will be extended by the
child class. All the methods can be inherited.
Example – 161
<?php class A {
public function printItem($string) {
echo ' Hi : ' .$string;
}
public function printPHP() {
echo 'I am from Covai' .PHP_EOL;
} }
class B extends A {
public function printItem($string)
{
Output
echo 'Hi: ' . $string .PHP_EOL;
} Hi : Raju
Abstract Classes:
An abstract class is a class that contains at least one abstract method. The abstract method is function
declaration without anybody and it has the only name of the method and its parameters.
There can be any number of methods in the class and we have to declare the class as abstract only
when there is an abstract method.
In an inheritance hierarchy, subclasses implement specific details, whereas the parent class defines the
framework its subclasses. The parent class also serves a template for common methods that will be
implemented by its subclasses. To make the parent classes more general and abstract, PHP provides
abstract method and abstract class.
Example – 162
<?php
abstract class Cars
{
public abstract function getCompanyName();
public abstract function getPrice();
}
class Baleno extends Cars
{
public function getCompanyName()
{
return "Maruthi Suzuki" . '<br/>';
}
public function getPrice()
{
return 720000 . '<br/>';
}
}
class Santro extends Cars {
public function getCompanyName()
{
return "Hyundai" . '<br/>';
}
public function getPrice()
{
return 300000 . '<br/>';
}
}
$car = new Baleno();
Output
$car1 = new Santro();
echo $car->getCompanyName(); Maruthi Suzuki
echo $car->getPrice(); 720000
Hyundai
echo $car1->getCompanyName(); 300000
echo $car1->getPrice();
?>
Example – 164
<?php The class "
destructors " was
class destructors
destroyed.
{
// Destructor
public function __destruct()
{
echo 'The class "' . __CLASS__ . '" was destroyed!';
}
}
// Create a new object
$obj = new destructors;
?>
❖ It starts out by looking at individual values and builds to a page that can generically access
any available form values.
❖ During the course of the article, you'll look at how different types of HTML form elements
provide information that PHP can access.
❖ HTML Forms are required, when you want to collect some data from the site visitor. For example, during
user registration you would like to collect information such as name, email address, credit card, etc.
❖ A form will take input from the site visitor and then will post it to a back-end application such
as CGI, ASP Script or PHP script etc. The back-end application will perform required processing
on the passed data based on defined business logic inside the application.
❖ There are various form elements available like text fields, textarea fields, drop-down menus,
radio buttons, checkboxes, etc.
The HTML <form> tag is used to create an HTML form and it has following syntax:
<form action="Script URL" method="GET|POST">
form elements like input, textarea etc.
</form>
Form Attributes
Apart from common attributes, following is a list of the most frequently used form attributes:
Attribute Description
method Method to be used to upload data. The most frequently used are GET & POST methods.
target Specify the target window or frame where the result of the script will be displayed.
It takes values like _blank, _self, _parent etc.
enctype You can use the enctype attribute to specify how the browser encodes the data before
it sends it to the server.
Form Controls
There are different types of form controls that you can use to collect data using HTML form:
• Text Input Controls • Select Box Controls • Clickable Buttons
• Checkboxes Controls • File Select boxes • Submit and Reset Button
• Radio Box Controls • Hidden Controls
Text Input Controls There are three types of text input used on forms:
Single-line text input controls - This control is used for items that require only one line of user
input, such as search boxes or names. They are created using
HTML <input> tag.
Password input controls - This is also a single-line text input but it masks the character as
soon as a user enters it. They are also created using HTMl <input>
tag.
Multi-line text input controls - This is used when the user is required to give details that may
be longer than a single sentence. Multi-line input controls are
created using HTML <textarea> tag.
Example – 165 Here is a basic example of a single-line text input used to take first name and last name:
<html>
<head>
<title>Text Input Control</title>
</head>
<body>
<form >
First name: <input type="text" name="first_name" />
<br>
Last name: <input type="text" name="last_name" />
</form>
</body>
</html>
This will produce the following result:
Attributes
Following is the list of attributes for <input> tag for creating text field.
Attribute Description
type Indicates the type of input control and for text input control it will be set to text.
name Used to give a name to the control which is sent to the server to be recognized and get the value.
value This can be used to provide an initial value inside the control.
size Allows to specify the width of the text-input control in terms of characters.
maxlength Allows to specify the maximum number of characters a user can enter into the text box.
Password Input controls
This is also a single-line text input but it masks the character as soon as a user enters it. They are also
created using HTML <input> tag but type attribute is set to password.
Example – 166 Here is a basic example of a single-line password input used to take user password:
<html>
<head>
<title>Password Input Control</title>
</head>
<body>
<form >
User ID : <input type="text" name="user_id" />
<br>
Password: <input type="password" name="password" />
</form>
</body>
</html>
This will produce the following result:
User ID : Password:
Attributes
Following is the list of attributes for <input> tag for creating password field.
Attribute Description
name Used to give a name to the control which is sent to the server to be recognized and
get the value.
value This can be used to provide an initial value inside the control.
size Allows to specify the width of the text-input control in terms of characters.
maxlength Allows to specify the maximum number of characters a user can enter into the text box.
Example – 167 Here is a basic example of a multi-line text input used to take item description:
<html>
<head>
<title>Multiple-Line Input Control</title>
</head>
<body>
<form>
Description: <br />
<textarea rows="5" cols="50" name="description"> Enter description here...
</textarea>
</form>
</body>
</html>
Attributes
Following is the list of attributes for <textarea> tag.
Attribute Description
name Used to give a name to the control which is sent to the server to be recognized and get the value.
rows Indicates the number of rows of text area box.
Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also created
using HTML <input> tag but type attribute is set to checkbox.
Example – 168 Here is an example HTML code for a form with two checkboxes:
<html>
<head>
<title>Checkbox Control</title></head>
<body>
<form>
<input type="checkbox" name="maths" value="on"> Maths
<input type="checkbox" name="physics" value="on"> Physics
</form>
</body> </html>
This will produce the following result:
Maths Physics
Attributes
Following is the list of attributes for <checkbox> tag.
Attribute Description
type Indicates the type of input control and for checkbox input control it will be set to checkbox.
name Used to give a name to the control which is sent to the server to be recognized and get
the value.
Example – 169 Here is example HTML code for a form with two radio buttons:
<html>
<head>
<title>Radio Box Control</title>
</head>
<body>
<form>
<input type="radio" name="subject" value="maths"> Maths
<input type="radio" name="subject" value="physics"> Physics
</form>
</body>
</html>
This will produce the following result:
Maths Physics
Attributes
Following is the list of attributes for radio button.
Attribute Description
type Indicates the type of input control and for checkbox input control it will be set to radio.
name Used to give a name to the control which is sent to the server to be recognized and get the value.
value The value that will be used if the radio box is selected.
checked Set to checked if you want to select it by default.
Select Box Control
A select box, also called drop down box which provides option to list down various options in the form
of drop down list, from where a user can select one or more options.
Example – 170 Here is example HTML code for a form with one drop down box
<html>
<head>
<title>Select Box Control</title> </head>
<body>
<form>
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select> </form>
</body>
</html>
This will produce the following result:
Maths
Attributes
Following is the list of important attributes of <select> tag:
Attribute Description
name Used to give a name to the control which is sent to the server to be recognized
and get the value.
size This can be used to present a scrolling list box.
multiple If set to "multiple" then allows a user to select multiple items from the menu.
Following is the list of important attributes of <option> tag:
Attribute Description
value The value that will be used if an option in the select box box is selected.
selected Specifies that this option should be the initially selected value when the page loads.
label An alternative way of labelling options
Button Controls
There are various ways in HTML to create clickable buttons. You can also create a clickable button using
<input> tag by setting its type attribute to button. The type attribute can take the following values:
Type Description
submit This creates a button that automatically submits a form.
reset This creates a button that automatically resets form controls to their initial values.
button This creates a button that is used to trigger a client-side script when the user clicks that button.
image This creates a clickable button but we can use an image as background of the button.
Example – 171
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
<input type="button" name="ok" value="OK" />
<input type="image" name="imagebutton" src="/html/images/logo.png" />
</form>
</body>
</html>
Now the question is, how these complex communication happens between server and browser?
While in complete HTTP basic auth process server and browser communicate via HTTP header. Below
are the step by step process with HTTP header on how server and browser communicate in HTTP basic
authentication process:
1. User request for the HTTP basic author protected page via web browser.
2. Server send the following header to browser so that browser can ask user to enter the
password:
if (!isset($_SERVER['PHP_AUTH_USER']))
exit;
else
password.</p>";
?>
Hello Raja.
Example – 173
<?php
$realm = 'Restricted area';
//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');
if (empty($_SERVER['PHP_AUTH_DIGEST']))
{
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
die('Text to send if user hits Cancel button');
}
// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');
// generate the valid response
PHP Cookies:
A cookie is often used to identify a user.
What is a Cookie?
• Cookies are text files stored on the client computer and they are kept of use tracking purpose.
PHP transparently supports HTTP cookies.
• There are three steps involved in identifying returning users:
• Server script sends a set of cookies to the browser. For Example, name, age, or identification
number etc.
Value - This sets the value of the named variable and is the content that you actually want to store.
Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time
cookie will become inaccessible. If this parameter is not set, then cookie will
automatically expire when the Web Browser is closed.
Path - This specifies the directories for which the cookie is valid. A single forward slash
Security - This can be set to 1 to specify that the cookie should only be sent by secure transmission using
HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
The following example will create two cookies name and age. These cookies will expire after an hour.
Example – 174
<?php
setcookie("name", "John", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html> <head> <title>Setting Cookies with PHP</title> </head>
<body> <?php echo "Set Cookies"?> </body> </html>
Example – 175
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
You can use isset() function to check if a cookie is set or not.
Example – 176
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?> </body> </html>
Example – 177
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
// set the expiration date to one hour ago setcookie("user", "", time()-3600);
?>
<html> <head>
<title>Deleting Cookies with PHP</title> </head>
<body> <?php echo "Deleted Cookies" ?>
</body> </html>
Example – 178
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false)
{
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}
else
{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
File Handling:
Opening a file:
• The fopen( ) function is used to open the file in PHP.
• The first parameter of this function contains the name of the file to be opened and the
second parameter specifies in which mode the file should be opened.
Example – 179
<html>
Mode Description
<head>
r Read only, start at the beginning of the file.
<body>
r++ Read, write at the beginning of the file.
<?php
w Write only, open the content of the file or
$file = fopen ("Welcome.txt", 'r'); creates a new file.
?> w++ Read Write, only open the content of the file
or create a new file.
</head> a Append.
</html>
Example – 180
<?php
$file = fopen(" test.txt", "r");
fclose($file);
?>
Check end of file: The end of the file by using feof( ) function checks if the end of the file has been reached.
Example – 181
<?php
$file = fopen("test.txt", "r");
//Output a line of the file until the end is reached
while(! feof($file))
{
echo fgets($file). "<br />";
}
fclose($file); ?>
Reading a file line by line: The fgets( ) function is used to read a single line from a file.
Example – 182
The output of the code above will be:
<html> Hello, this is a test file.
<body> There are three lines here.
<?php This is the last line.
$file = fopen("Welcome.txt", "r");
while( !eof($file))
{
echo fgets($file);
}
fclose($file);
?>
</body> </html>
Reading a file character by character: The function fgetc( ) used to read a file character by character.
Example – 183
<html> <body> <?php
$file = fopen("Welcome.txt", "r");
While( !eof($file))
{
echofgetc($file);
}
fclose($file);
?>
</body> </html>
Example – 185
<html> <head>
<title> Reading a page into an array</title>
</head>
<body>
<h1> Reading a page into an array</h1>
<?php
$data = file(" http:// www.php.net");
foreach($data as $number -> $line)
{
echo "line number", $line ;"<br>
}
?> </body> </html>
Example – 186
<html> <head>
<title> Getting file size</title>
</head>
<body>
<h1> Getting file size</h1>
<?php
echo "The file size.txt is" file size("file.txt") " bytes long";
?> </body> </html>
Example – 187
<html>
<head>
<title> Creating an upload file </title> </head>
<body>
<form action = "upload-file.php" Method = "post" enctype = "Multipart / form.data ">
<label for = "file"> filename : </label>
<input type = "file" name = "file" ie\ = "file" ></input><br>
<input type = "submit" name = "submit" value = "submit"> </input>
</form>
</body>
</html>
To read a remote file from php you have at least four options :
1. Use fopen() 2. Use file_get_contents()
3. CURL 4. Make your own function using php's socket functions.
First i need to warn you about something. You can only use fopen() and file_get_contents() when
fopen wrappers is enabled. This parameter is specified in the php.ini file and cannot be changed at
run time using ini_set(), To know whether you can use these two or not you can use the following
code to check the value of fopen wrapper setting.
Example
if (ini_get('allow_url_fopen') == '1')
{
// use fopen() or file_get_contents()
} else {
// use curl or your custom function
}
1 . Using fopen()
If you use fopen() to read a remote file the process is as simple as reading from a local file. The only
difference is that you will specify the URL instead of the file name. Take a look at the example below :
Example – 188
if ($fp = fopen('http://www.google.com/', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
} else {
}
Now, the code above use fread() function in the while loop to read up to 1024 bytes of data in a
single loop. That code can also be written like this :
Example – 189 // make sure the remote file is successfully opened before doing anything else
2. Using file_get_contents()
This is my favorite way of reading a remote file because it is very simple. Just call this function and
specify a url as the parameter. But make sure you remember to check the return value first to
determine if it return an error before processing the result
$content = file_get_contents('http://www.google.com/');
if ($content !== false)
{
// do something with the content
} else
URL stands for Uniform Resource Locator, and is
{
used to specify addresses on the World Wide
// an error happened Web. A URL is the fundamental network
identification for any resource connected to the
}
web (e.g., hypertext pages, images, and sound
3. CURL(Client Uniform Resource Locator) files). The protocol specifies how information
from the link is transferred.
The CURL library ('libcurl' which is the package name
on the server) is often used in PHP to access data from
RSS, in its current form, stands for Really Simple
outside web pages. Syndication and is a family of web formats to
Common uses include reading rss feeds or accessing publish frequently updated content. The RSS
Feed (as it is commonly known) can then be read
third-party API systems. libcurl currently supports the by the users feed reading software or by another
website which wishes to 'syndicate' the content
http, https, ftp, gopher, telnet, dict, file, and ldap of that feed.
protocols. Unlike the two methods above using CURL
cannot be said as straight forward. Although this library
is very useful to connect and communicate with many Gzip is a method of compressing files (making
them smaller) for faster network transfers. It is
different protocols it requires more effort to learn. And also a file format. Compression allows your web
server to provide smaller file sizes which load
another problem is that not all web host have this
faster for your website users. Enabling gzip
library in their php installation. compression is a standard practice
4. Custom functions
In the worst case your server will have fopen wrappers disabled and don't have CURL library installed.
In this sad situation you just have to make your own way.
Our function shall be named getRemoteFile() which takes only one parameter, the url for the remote
<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
echo "<p>Unable to open remote file for writing.\n";
exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>
Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To
do distributed logging like that, you should take a look at syslog().
Connection Handling:
Definition and Usage
The connection_status() function returns the current connection status.
Internally in PHP a connection status is maintained. There are 4 possible states:
0 - CONNECTION_NORMAL - connection is running normally
1 - CONNECTION_ABORTED - connection is aborted by user or network error
2 - CONNECTION_TIMEOUT - connection timed out
3 - CONNECTION_ABORTED & CONNECTION_TIMEOUT
Syntax connection_status()
✓ When a PHP script is running normally, the NORMAL state is active. If the remote client
disconnects, the ABORTED state flag is turned on.
✓ A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-
imposed time limit (see set time limit()) is hit, the TIMEOUT state flag is turned on.
✓ You can decide whether or not you want a client disconnect to cause your script to be aborted.
Sometimes it is handy to always have your scripts run to completion even if there is no remote
browser receiving the output.
✓ The default behaviour is however for your script to be aborted when the remote client disconnects.
✓ This behaviour can be set via the ignore_user_abortphp.ini directive as well as through the
corresponding php_valueignore_user_abort Apache httpd.conf directive or with the ignore
user abort() function.
✓ If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The
one exception is if you have registered a shutdown function using register shutdown
function().
✓ With a shutdown function, when the remote user hits his STOP button, the next time your
script tries to output something PHP will detect that the connection has been aborted and the
shutdown function is called.
✓ This shutdown function will also get called at the end of your script terminating normally, so
to do something different in case of a client disconnect you can use the connection abortedQ
function. This function will return TRUE if the connection was aborted.
✓ When the timer expires the script will be aborted and as with the above client disconnect case,
if a shutdown function has been registered it will be called.
✓ Within this shutdown function you can check to see if a timeout caused the shutdown function
to be called by calling the connection status() function.
✓ This function will return 2 if a timeout caused the shutdown function to be called.
✓ One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time.
✓ This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may
have broken the connection, but the script will keep running.
✓ If it then hits the time limit it will be aborted and your shutdown function, if any, will be called.
At this point you will find that connection status() returns 3.
Example – 192
<html>
<body>
<?php
switch (connection_status())
{
case CONNECTION_NORMAL:
$txt = 'Connection is in a normal state';
break;
case CONNECTION_ABORTED:
$txt = 'Connection aborted';
break;
case CONNECTION_TIMEOUT:
$txt = 'Connection timed out';
break;
case (CONNECTION_ABORTED & CONNECTION_TIMEOUT):
$txt = 'Connection aborted and timed out';
break;
default:
$txt = 'Unknown';
Connection is in a
break; normal state
}
echo $txt;
?> </body> </html>
MYSQL
Beginner
MySQL is an open source relational database management system (RDBMS) based on
Structured Query Language (SQL).
MySQL runs on virtually all platforms, including Linux, UNIX, and Windows. Although it
can be used in a wide range of applications, MySQL is most often associated with web-
based applications and online publishing and is an important component of an open
source enterprise stack called LAMP.
LAMP is a Web development platform that uses Linux as the operating system, Apache
as the Web server, MySQL as the relational database management system and PHP as
the object-oriented scripting language.
MySQL is a fast, easy to use relational database. It is currently the most popular open-
source database. It is very commonly used in conjunction with PHP scripts to create
powerful and dynamic server-side applications.
MySQL is used for many small and big businesses. It is developed, marketed and
supported by MySQL AB, a Swedish company. It is written in C and C++.
MySQL is becoming so popular because of these following reasons:
MySQL is an open-source database so you don't have to pay a single penny to use it.
MySQL is a very powerful program so it can handle a large set of functionality of the
most expensive and powerful database packages.
MySQL is customizable because it is an open source database and the open-source GPL
license facilitates programmers to modify the SQL software according to their own
specific environment.
MySQL is quicker than other databases so it can work well even with the large data set.
MySQL supports many OS with many languages like PHP, PERL, C, C++, JAVA, etc.
MySQL uses a standard form of the well-known SQL data language.
MySQL is very friendly with PHP, the most popular language for web development.
MySQL supports large databases, up to 50 million rows or more in a table.
The default file size limit for a table is 4GB, but you can increase this to a theoretical
limit of 8 million TB.
The data in a MySQL database are stored in tables. A table is a collection of related data,
and it consists of columns and rows.
History
MySQL was created by a Swedish company, MySQL AB, founded by David Axmark, Allan
Larsson and Michael "Monty" Widenius. Original development of MySQL by Widenius
and Axmark began in 1994.
MySQL AB was acquired by Sun Microsystems in 2008 and then by Oracle when it
bought Sun in 2010. Developers can still use MySQL under the GNU General Public
License (GPL), but enterprises must obtain a commercial license from Oracle.
MySQL Data Types In MySQL there are three main data types: text, number & Date/Time types.
Text types:
Data type Description
Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is
CHAR(size)
specified in parenthesis. Can store up to 255 characters
Holds a variable length string (can contain letters, numbers, and special characters). The maximum
VARCHAR(size)
size is specified in parenthesis. Can store up to 255 characters.
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT Holds a string with a maximum length of 65,535 characters
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is
ENUM(x,y,z,etc.)
inserted that is not in the list, a blank value will be inserted.
SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice
Number types:
Data type Description
TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified
in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be
specified in parenthesis
MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits
may be specified in parenthesis
FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be
specified in the size parameter.
DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be
specified in the size parameter.
DECIMAL(size,d) A DOUBLE stored as a string, allowing for a fixed decimal point. The maximum number of
digits may be specified in the size parameter.
Date types:
Data type Description
*A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix
TIMESTAMP() epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MI:SS
Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC
Create Database
Syntax: CREATE DATABASE database_name;
Example: CREATE DATABASE Student;
SELECT Database
SELECT Database is used in MySQL to select a particular database to work with. This query is
used when multiple databases are available with MySQL Server.
You can use SQL command USE to select a particular database.
Syntax: USE database_name;
Example: USE customers;
Drop Database
You can drop/delete/remove a MySQL database easily with the MySQL command. You should be
careful while deleting any database because you will lose your all the data available in your database.
Syntax: DROP DATABASE database_name;
Example: DROP DATABASE employees;
CREATE TABLE
The MySQL CREATE TABLE command is used to create a new table into the database. A table creation
command requires three things:
1. Name of the table
2. Names of fields
3. Definitions for each field
Syntax: CREATE TABLE table_name (column_name column_type...);
Example:
CREATE TABLE cus_tbl(
cus_id INT NOT NULL AUTO_INCREMENT,
cus_firstname VARCHAR(100) NOT NULL,
cus_surname VARCHAR(100) NOT NULL,
PRIMARY KEY ( cus_id )
);
See the created table: The table already created: SHOW tables;
See the table structure: The table already created: DESCRIBE cus_tbl;
ADD a column in the table
Syntax: ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ];
Database Connections:
✓ MySQLi extension (the "i" stands for improved)
✓ PDO (PHP Data Objects)
mysql_connect — Open a connection to a MySQL Server
Description Resource mysql_connect ( [ string $server = ini_get("mysql.default_host")
[, string $username = ini_get("mysql.default_user")
[, string $password = ini_get("mysql.default_password")
[, bool $new_link = false
[, int $client_flags = 0 ]]]]] )
Opens or reuses a connection to a MySQL server.
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Parameters
server
The MySQL server. It can also include a port number.
e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost.
If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'.
In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.
username
The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter
is ignored and the name of the user that owns the server process is used.
password
The password. Default value is defined by mysql.default_password. In SQL safe mode, this
parameter is ignored and empty password is used.
new_link
The new_link parameter modifies this behavior and makes mysql_connect() always open a new
link, even if mysql_connect() was called before with the same parameters. In SQL safe mode,
this parameter is ignored.
client_flags
The client_flags parameter can be a combination of the following constants: 128 (enable LOAD
DATA LOCAL handling),
MYSQL_CLIENT_SSL,
MYSQL_CLIENT_COMPRESS,
MYSQL_CLIENT_IGNORE_SPACE or
MYSQL_CLIENT_INTERACTIVE.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
// Check connection
if (!$conn) {
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
} else {
mysqli_close($conn);
?>
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
email VARCHAR(50),
reg_date TIMESTAMP
)";
$conn->exec($sql);
catch(PDOException $e)
$conn = null;
?>
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
}
catch(PDOException $e)
{ // roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Name"
/><br>
<input type="number" name="m1" id="m1" class="form-control"
placeholder="Mark1" /><br>
<input type="number" name="m2" id="m2" placeholder="Mark2" class="form-
control" /><br>
<input type="number" name="m3" id="m3" placeholder="Mark3" class="form-
control" onchange="cal();" /><br>
$("#total").val(total);
$("#avg").val(avg);
}
</script>
<div class="col-md-4">
<table class="table table-striped">
<tr>
<th>S.No</th>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Mark3</th>
<th>Total</th>
<th>Average</th>
<th>Result</th>
</tr>
<?php
$query = "SELECT * FROM m1";
$res = mysqli_query($db,$query);
$row = mysqli_num_rows($res);
$i = 1;
if($row > 0) {
while($list = mysqli_fetch_assoc($res)){
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $list['name']; ?></td>
<td><?php echo $list['m1']; ?></td>
<td><?php echo $list['m2']; ?></td>
<td><?php echo $list['m3']; ?></td>
<td><?php echo $list['total']; ?></td>
<td><?php echo $list['avg']; ?></td>
<td><?php echo $list['result']; } } ?></td>
</tr>
</table>
</div>
</body>
<html>
//add.php
<html>
<body>
<?php
include 'database.php';
$name= $_POST['name'];
$m1 = $_POST['m1'];
$m2 = $_POST['m2'];
$m3 = $_POST['m3'];
$total = $_POST['total'];
$avg = $_POST['avg'];
$result = $_POST['result'];
$query = "INSERT INTO m1(name,m1,m2,m3,total,avg,result)
VALUES('$name','$m1','$m2','$m3','$total','$avg','$result')";
$res = mysqli_query($db,$query);
if(isset($res)){
echo "Data Saved";
header('location:add_mark.php');
}
?>
</body>
</html>
//database Connection
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "mark1";
$db = mysqli_connect($host,$user,$password,$database);
if(!isset($db)){
echo "Database Not Connect";
}
?>
// add_marks
<?php
include 'database.php';
?>
<html>
<head>
<style type="text/css">
#in_class input{
padding: 5px;
margin-top: 10px;
border-radius: 3px;
}
button{
background: green;
color: white;
padding: 5px;
}
</style>
</head>
<body>
<form action="add.php" method="post">
<div id="in_class" class="in_class">
<input type="text" name="name" placeholder="Name" /><br>
<input type="number" name="m1" id="m1" placeholder="Mark1" /><br>
<input type="number" name="m2" id="m2" placeholder="Mark2" /><br>
<input type="number" name="m3" id="m3" placeholder="Mark3"
onchange="cal();" /><br>
<script type="text/javascript">
function cal() {
var m1 = document.getElementById('m1').value;
var m2 = document.getElementById('m2').value;
var m3 = document.getElementById('m3').value;
$("#total").val(total);
$("#avg").val(avg);
}
</script>
<br><br>
<table border="1">
<tr>
<th>S.No</th>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Mark3</th>
<th>Total</th>
<th>Average</th>
<th>Result</th>
</tr>
<?php
$query = "SELECT * FROM m1";
$res = mysqli_query($db,$query);
$row = mysqli_num_rows($res);
$i = 1;
if($row > 0) {
while($list = mysqli_fetch_assoc($res)){
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $list['name']; ?></td>
<td><?php echo $list['m1']; ?></td>
<td><?php echo $list['m2']; ?></td>
<td><?php echo $list['m3']; ?></td>
<td><?php echo $list['total']; ?></td>
<td><?php echo $list['avg']; ?></td>
<td><?php echo $list['result']; } } ?></td>
</tr>
</table>
</body>
<html>
---x---x---x---
Page | 1
Difference between PHP and JavaScript
PHP and JavaScript both are used for different purposes. As we have discussed earlier that PHP is a server-side
script, whereas, JavaScript is a client-side script. Below are some differences between PHP and JavaScript has
given:
PHP JavaScript
PHP performs all the server-side functions like JavaScript is designed to create an interactive
authentication, building custom web content, web application without interacting with the
handling request, etc. server
PHP can combine with HTML only. JavaScript can combine with HTML, AJAX and
also with XML.
PHP is used for back-end purpose only. JavaScript is used for both front-end and back-
end.
In PHP, the code will be available and viewed after A JavaScript code can be viewed Even after the
it is interpreted by the server. output is interpreted.
It is synchronous by nature and waits for I/O JavaScript is asynchronous by nature and does
operation to execute. not wait for I/O operation to execute.
Page | 2
Which are scripting languages?
A scripting or script language is a programming language that supports scripts; programs written for a
special run-time environment that automate the execution of tasks that could alternatively be executed
one-by-one by a human operator.
XML
XML stands for Extensible Markup Language and is a text-based markup language derived from Standard
Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than specifying how to
display it like HTML tags, which are used to display the data. XML is not going to replace HTML in the near
future, but it introduces new possibilities by adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of systems and solutions
Page | 3
XML is extensible − XML allows you to create your own self-descriptive
tags, or language, that suits your application.
XML carries the data, does not present it − XML allows you to store the data irrespective of how
it will be presented.
XML is a public standard − XML was developed by an organization called the
World Wide Web Consortium (W3C) and is available
as an open standard.
What is XML?
• XML stands for eXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to store and transport data
• XML was designed to be self-descriptive
• XML is a W3C Recommendation
</note>
Page | 4
The Difference between XML and HTML
XML and HTML were designed with different goals:
• XML was designed to carry data - with focus on what data is
• HTML was designed to display data - with focus on how data looks
• XML tags are not predefined like HTML tags are
XML is Extensible
Most XML applications will work as expected even if new data is added (or removed).
Imagine an application designed to display the original version of note.xml (<to> <from> <heading>
<data>). Then imagine a newer version of note.xml with added <date> and <hour> elements, and a
removed <heading>. The way XML is constructed, older version of the application can still work:
<note>
Old Version
<date>2015-09-01</date> Note
<hour>08:30</hour> To: Tamil
From: Janu
<to>Tamil</to> Head: (none)
<from>Janu</from> Don't forget me this weekend!
Page | 5
✓ XML can be used for offloading and reloading of databases.
✓ XML can be used to store and arrange the data, which can customize your data handling needs.
✓ XML can easily be merged with style sheets to create almost any desired output.
✓ Virtually, any type of data can be expressed as an XML document.
What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format that is both human-
readable and machine-readable. So what exactly is a markup language? Markup is information added to
a document that enhances its meaning in certain ways, in that it identifies the parts and how they relate
to each other. More specifically, a markup language is a set of symbols that can be placed in the text of a
document to demarcate and label the parts of that document.
Following example shows how XML markup looks, when embedded in a piece of text −
<message>
<text>Hello, world!</text>
</message>
This snippet includes the markup symbols, or the tags such as <message>...</message> and <text>...
</text>. The tags <message> and </message> mark the start and the end of the XML code fragment. The
tags <text> and </text> surround the text Hello, world!.
Is XML a Programming Language?
A programming language consists of grammar rules and its own vocabulary which is used to create
computer programs. These programs instruct the computer to perform specific tasks. XML does not
qualify to be a programming language as it does not perform any computation or algorithms. It is usually
stored in a simple text file and is processed by special software that is capable of interpreting XML.
The following diagram depicts the syntax rules to write different types of markup and text in an XML
document. Let us see each component of the above diagram in detail.
aXML Declaration
The XML document can optionally have an XML declaration. It
is written as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
Where version is the XML version and encoding specifies the
character encoding used in the document.
Page | 6
Syntax Rules for XML Declaration
• The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written in lower-case.
• If document contains XML declaration, then it strictly needs to be the first statement of the XML document.
• The XML declaration strictly needs be the first statement in the XML document.
• An HTTP protocol can override the value of encoding that you put in the XML declaration.
Tags and Elements
An XML file is structured by several XML-elements, also called XML-nodes or XML-tags. The names of
XML-elements are enclosed in triangular brackets < > as shown below −
<element>
Syntax Rules for Tags and Elements
Element Syntax − Each XML-element needs to be closed either with start or with end elements as
shown below −
<element>....</element>
or in simple-cases, just this way −
<element/>
Nesting of Elements − An XML-element can contain multiple XML-elements as its children, but the
children elements must not overlap. i.e., an end tag of an element must have the same name as that of
the most recent unmatched start tag.
The Following example shows incorrect nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>Tutorials
<contact-info>
</company>
The Following example shows correct nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPHP</company>
<contact-info>
Root Element − An XML document can have only one root element. For example, following is not a correct
XML document, because both the x and y elements occur at the top level without a root element
<root>
Page | 7
<x>...</x>
<y>...</y>
</root>
Case Sensitivity − The names of XML-elements are case-sensitive. That means the name of the start and
the end elements need to be exactly in the same case.
For example, <contact-info> is different from <Contact-Info>
XML Attributes
An attribute specifies a single property for the element, using a name/value pair. An XML-element can
have one or more attributes. For example −
<a href = "http://www.tutorialspoint.com/">Tutorialspoint!</a>
Here href is the attribute name and http://www.tutorialspoint.com/ is attribute value.
Syntax Rules for XML Attributes
• Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are considered
two different XML attributes.
• Same attribute cannot have two values in a syntax. The following example shows incorrect
syntax because the attribute b is specified twice
<a b = "x" c = "y" b = "z">....</a>
• Attribute names are defined without quotation marks, whereas attribute values must always
appear in quotation marks. Following example demonstrates incorrect xml syntax
<a b = x>....</a>
XML References
References usually allow you to add or include additional text or markup in an XML document.
References always begin with the symbol "&" which is a reserved character and end with the symbol
";". XML has two types of references −
Entity References − An entity reference contains a name between the start and the end delimiters. For
example & where amp is name. The name refers to a predefined string of text and/or markup.
Character References − These contain references, such as A, contains a hash mark (“#”) followed by
a number. The number always refers to the Unicode code of a character. In this case, 65 refers to
alphabet "A".
Page | 8
AJAX
AJAX is a developer's dream, because
you can:
• Update a web page without reloading
the page
• Request data from a server - after the
page has loaded
• Receive data from a server - after the
page has loaded
• Send data to a server - in the
background
What is AJAX?
✓ AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better,
faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
✓ Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and
JavaScript for dynamic content display.
✓ Conventional web applications transmit information to and from the server using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new
information from the server.
✓ With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results,
and update the current screen. In the purest sense, the user would never know that anything was
even transmitted to the server.
✓ XML is commonly used as the format for receiving server data, although any format, including
plain text, can be used.
✓ AJAX is a web browser technology independent of web server software.
✓ A user can continue to use the application while the client program requests information from
the server in the background.
✓ Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient
event trigger.
✓ Data-driven as opposed to page-driven.
Page | 9
Rich Internet Application Technology
AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting tremendous industry
momentum and several tool kit and frameworks are emerging. But at the same time, AJAX has browser
incompatibility and it is supported by JavaScript, which is hard to maintain and debug.
AJAX is Based on Open Standards
AJAX is based on the following open standards:
Browser-based presentation using HTML and Cascading Style Sheets (CSS).
Data is stored in XML format and fetched from the server.
Behind-the-scenes data fetches using XML Http Request objects in the browser.
JavaScript to make everything happen.
AJAX Technologies
AJAX cannot work independently. It is used in combination with other technologies to create interactive webpages.
JavaScript
✓ Loosely typed scripting language.
✓ JavaScript function is called when an event occurs in a page.
✓ Glue for the whole AJAX operation.
DOM
✓ API for accessing and manipulating structured documents.
✓ Represents the structure of XML and HTML documents.
CSS
✓ Allows for a clear separation of the presentation style from the content and may be changed
programmatically by JavaScript.
✓ XML HttpRequest
✓ JavaScript object that performs asynchronous interaction with the server.
PHP and AJAX Example
<!DOCTYPE html>
<html> <head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
Page | 10
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML =
this.responseText;
}
}
xmlhttp.open("GET", "gethint.php?q="+str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form> First name: <input type="text" onkeyup="showHint(this.value)"> </form>
<p>Suggestions: <span id="txtHint"></span></p> </body> </html>
Page | 11
What is Ajax in JavaScript?
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and
more interactive web applications with the help of XML, HTML, CSS, and Java Script. Ajax uses XHTML for
content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content
display.
What is the jquery?
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal
and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works
across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed
the way that millions of people write JavaScript.
What is Javascript and jquery?
Javascript is a programming language whereas jQuery is a framework to help make writing in javascript
easier. It's particularly useful for simply traversing the DOM in an HTML page.
jQuery is a wrapper of JavaScript, with much pre-written functionality and DOM traversing
CSS
What is CSS?
CSS stands for Cascading Style Sheets
CSS describes how HTML elements are to be displayed on screen, paper, or in other media
CSS saves a lot of work. It can control the layout of multiple web pages all at once
External stylesheets are stored in CSS files
CSS is a language that describes the style of an HTML document.
CSS describes how HTML elements should be displayed.
Why Use CSS?
CSS is used to define styles for your web pages, including the design, layout and variations in
display for different devices and screen sizes.
CSS Solved a Big Problem
HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
Page | 12
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a
nightmare for web developers. Development of large websites, where fonts and color information
were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS removed the style formatting from the HTML page!
CSS Saves a Lot of Work!
The style definitions are normally saved in external .css files.
With an external stylesheet file, you can change the look of an entire website by changing just
one file!
CSS Syntax
A CSS rule-set consists of a selector and a declaration block:
Example
In this example all <p> elements will be center-aligned, with a red text color:
p {
color: red;
text-align: center;
}
Node.js
Node.js was written initially by Ryan Dahl in 2009, about thirteen years after the introduction of the first
server-side JavaScript environment, Netscape's LiveWire Pro Web. The initial release supported only
Linux and Mac OS X. Its development and maintenance was led by Dahl and later sponsored by Joyent.
Page | 13
ECMAScript
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMAScript is the official name of the language.
From 2015 ECMAScript is named by year (ECMAScript 2015).
ECMA Script History
The ECMAScript specification is a standardized specification of a scripting language developed by Brendan
Eich of Netscape; initially it was named Mocha, later LiveScript, and finally JavaScript. In December 1995,
Sun Microsystems and Netscape announced JavaScript in a press release. The first edition of ECMA-262
was adopted by the ECMA General Assembly in June 1997. Several editions of the language standard have
been published since then. The name "ECMAScript" was a compromise between the organizations
involved in standardizing the language, especially Netscape and Microsoft, whose disputes dominated the
early standards sessions. Eich commented that "ECMAScript was always an unwanted trade name that
sounds like a skin disease." While both JavaScript and JScript aim to be compatible with ECMAScript, they
also provide additional features not described in the ECMA specifications.
Latest June 2018 ECMAScript 2018 (ES2018) 9th Edition
JavaScript vs. ECMA Script
JavaScript
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first
appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of
the language has been embedded in Netscape, Internet Explorer, and other web browsers.
The standard of scripting languages like JavaScript is ECMAScript.
ECMAScript
The full form of ECMA is European Computer Manufacturer's Association. ECMAScript is a
Standard for scripting languages such as JavaScript, JScript, etc. It is a trademark scripting
language specification. JavaScript is a language based on ECMAScript. A standard for
scripting languages like JavaScript, JScript is ECMAScript. JavaScript is considered as one of
the most popular implementations of ECMAScript.
• ECMAScript: Sun (now Oracle) had a trademark on the name“JavaScript” (which led to
Microsoft calling its JavaScript dialect “JScript”). Thus, when it came to standardizing the
language, a different name had to be used. Instead, “ECMAScript” was chosen, because
the corresponding standard is hosted by ECMA International (see below). In practice, the
terms “ECMAScript” and “JavaScript” are interchangeable. If JavaScript means
Page | 14
“ECMAScript as implemented by Mozilla and others” then the former is a dialect of the
latter. The term “ECMAScript” is also frequently used to denote language versions (such
as ECMAScript 5).
• ECMA-262: The ECMA International (a standards organization) has created the ECMA-
262 standard which is the official specification of the ECMAScript language.
• ECMA’s Technical Committee 39 (TC39): is the group of people (Brendan Eich and
others) who develop the ECMA-262 standard.
• ECMAScript 3 (December 1999). This is the version of ECMAScript that most browsers
support today. It introduced many features that have become an inherent part of the
language:
• regular expressions, better string handling, new control statements, try/catch
exception handling, tighter definition of errors, formatting for numeric output and
other enhancements.
• ECMAScript 4 (abandoned July 2008). ECMAScript 4 was developed as the next
version of JavaScript, with a prototype written in ML. However, TC39 could not agree on
its feature set. To prevent an impasse, the committee met at the end of July 2008 and
came to an accord, summarized in four points
1. Develop an incremental update of ECMAScript [which became ECMAScript 5.
2. Develop a major new release, which was to be more modest than ECMAScript 4, but much
larger in scope than the version after ECMAScript 3. This version has been code-
named Harmony, due to the nature of the meeting in which it was conceived.
3. Features from ECMAScript 4 that would be dropped: packages, namespaces, early
binding.
4. Other ideas were to be developed in consensus with all of TC39.
• The ECMAScript 4 developers agreed to make Harmony less radical than ECMAScript
4, the rest of TC39 agreed to keep moving things forward.
• ECMAScript 5 (December 2009). This version brings several enhancements to the
standard library and even updated language semantics via a strict mode.
• currently browsers are supporting upto ES5 only.
ECMAScript 6(2015)
• ES6 is an next-gen of JavaScript, the ecma technical committee 39 governs ecma
specification, they discovered new features to the javascript.
• ES6 can`t compile directly in browsers, so need an compiler from ES6 to ES5, for that
compiling using babel, it produce the browser compatible javascript.
Page | 15