What Is JavaScript To Print
What Is JavaScript To Print
JavaScript advantages
Fast speed: JavaScript is executed on the client side that’s why it is very fast.
Easy to learn: JavaScript is easy to learn. Any one which have basic knowledge of programming can easily learn
JavaScript.
Versatility: It refers to lots of skills. It can be used in a wide range of applications.
Browser Compatible: JavaScript supports all modern browsers. It can execute on any browser and produce same result.
Server Load: JavaScript reduce the server load as it executes on the client side.
Rich interfaces: JavaScript provides the drag and drop functionalities which can provides the rich look to the web pages.
Popularity: JavaScript is a very popular web language because it is used every where on the web.
Regular Updates: JavaScript updated annually by ECMA.
JavaScript disadvantages
Code Visibility: JavaScript code is visible to every one and this is the biggest disadvantage of JavaScript.
Stop Render: One error in JavaScript code can stop whole website to render.
No Multiple Inheritance: JavaScript only support single inheritance.
1
Comparison between server-side and client-side scripting
Occurrence It happens when a user’s browser initiates It happens when the browser possesses all the
a server request. Dynamic pages are then codes and the page in later changed according
created based on several conditions. to the user’s input.
Execution The scripting process for the server side is The scripting process of client server is
done on remote computer and hence the executed on a local computer and thus the
response is comparatively slower than the response is comparatively quicker when
client side one. compared to server side scripting.
Operation A server can carry out a server-side script, A browser can perform the client-side scripting
but cannot perform the client side after receiving the page sent by the server.
scripting.
Connection It helps in connecting to the databases It does not connect to the databases that are
to the that are already present in the web on the web server.
database server.
Suitability It is excellent for any area that requires It is excellent for any case which requires user
loading of dynamic data. interaction.
Access To It has access to all the files present in the It has no access to all the files present in the
Files web server. web server.
Security It is more secure than client side scripting It is less secure because the scripts are usually
as the server side scripts are usually not hidden from the client end.
hidden from the client end.
2
We can understand this more clearly with the help of an example, how to add JavaScript to html Example:
<html>
<head>
<title> page title</title>
<script>
document.write(“Welcome to our first page”);
</script>
</head>
<body>
<p>Here we saw how to add JavaScript in the head section </p>
</body> </html>
Output:
We can also define the JavaScript code in the <body> tags or body section like this:
<!DOCTYPE html >
<html>
<head>
<title> page title</title>
</head>
<body> <script>
document.write(“Welcome to our first page”);
</script>
<p>In this example we saw how to add JavaScript in the body section </p>
</body>
</html>
Output
3
2. Inline code:-
Generally, this method is used when we have to call a function in the HTML event attributes. There are many cases (or
events) in which we have to add JavaScript code directly eg.,onmouseover event, onclick, etc.
Let’s see with the help of an example, how we can add JavaScript directly in the html without using the <script>.... </script>
tag.
Let’s look at the example.
<!DOCTYPE html >
<html> <head><title> page title</title>
</head>
<body>
<p>
<a href= ‘‘#” onclick= “alert(‘Welcome !’);”>Click Me</a>
</p>
<p> in this example we saw how to use inline JavaScript or directly in an HTML tag. </p> </body>
</html>
Output
3. External file:-
We can also create a separate file to hold the code of JavaScript with the (.js) extension and later incorporate/include it into
our HTML document using the src attribute of the <script> tag. It becomes very helpful if we want to use the same code in
multiple HTML documents. It also saves us from the task of writing the same code over and over again and makes it easier
to maintain web pages.
In this example, we will see how we can include an external JavaScript file in an HTML document. Let’s understand through
a simple example.
<html> <head>
<meta charset= “utf-8”>
<title>Including a External JavaScript File</title>
</head> <body><form>
<input type= “button” value=”Result” onclick= “display()”/>
</form>
<script src= “hello.js”>
</script> </body> </html>
Now let’s create separate JavaScript file Hello.js in the same folder:
function display() {
alert(“Hello World!”);
}
Both of the above programs are saved in the same folder, but you can also store JavaScript code in a separate folder, all just
you need to provide the address/path of the (.js) file in the src attribute of <script> tag.
Output is:
4
Advantages of External JavaScript
There will be following benefits if a user creates an external JavaScript:
It helps in the reusability of code in more than one HTML file.
It allows easy code readability.
It is time-efficient as web browsers cache the external js files, which further reduces the page loading time.
It enables both web designers and coders to work with html and js files parallelly and separately, i.e., without facing
any code conflictions.
The length of the code reduces as only we need to specify the location of the js file.
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add information about the code, warnings or
suggestions so that end user can easily interpret the code. The JavaScript comment is ignored by the JavaScript engine i.e.
embedded in the browser.
Types of JavaScript Comments
There are two types of comments in JavaScript.
1. Single-line Comment
2. Multi-line Comment
JavaScript Single line Comment
It is represented by double forward slashes (//). It can be used before and after the statement. Let’s see the example of
single-line comment i.e. added before the statement.
<script>
// It is single line comment document.write(“hello javascript”);
</script>
5
JavaScript non-primitive data types
6
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands. For example: var sum=15+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
7
JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.
Operator Description Example
= Assign 10 + 10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
Functions and control structure if-else, if-elseif, switch-case, for, while, do while loop
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are three forms of if
statement in JavaScript.
1. If Statement
2. If else statement
3. If else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is given below.
if(expression){
//content to be evaluated
}
Let’s see the simple example of if statement in JavaScript.
<script> var a=20; if(a>10){
document.write(“value of a is greater than 10”);
}
</script>
if(expression){
//content to be evaluated if condition is true
} else{
//content to be evaluated if condition is false
}
8
Let’s see the example of if-else statement in JavaScript to find out the even or odd number.
<script> var a=40; if(a%2==0){
document.write(“a is even number”);
} else{
document.write(“a is odd number”);
} </script>
case '3':
alert("Tuesday");
break;
case '4':
alert("Wednesday");
break;
case '5':
alert("Thursday");
break;
case '6':
alert("Friday");
break;
case '7':
alert("Saturday");
break;
default:
alert("wrong number");
}
document.getElementById("number").focus();
}
}
</script>
</head>
<body>
<form>
Enter a number from 1 to 7 in the box below:
<input type="text" id="number"><br>
<input type="button" value="print" onclick="calculate()">
</form>
</body>
</html>
10
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the code compact.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is known.
The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
Let’s see the simple example of for loop in javascript.
<script>
for (i=1; i<=3; i++)
{
document.write(i + “<br/>”) ;
}
</script>
Output:
1
2
3
JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number of iteration is
not known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.
<script> var i=10;
while (i<=15)
{
document.write(i + “<br/>”);
i++;
}
</script>
Output:
10
11
12
13
14
15
JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code is executed at
least once whether condition is true or false. The syntax of do while loop is given below.
do {
code to be executed
} while (condition);
Let’s see the simple example of do while loop in javascript.
11
<script>
var i=21;
do {
document.write(i + “<br/>”);
i++;
}while (i<=23);
</script>
Output:
21
22
23
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading body of the page
12
By using an Object constructor
Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this
keyword.
The ‘this’ keyword refers to the current object.
The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){ this.id=id;
this.name=name;
this.salary=salary; }
e=new emp(103, “Anil koirala”,30000);
document.write(e.id+” “+e.name+” “+e.salary);
</script>
Output of the above example
103 Anil koirala 30000
13
The following form uses JavaScript codes to validate the given form.
<html> <head><title> SignUp Page</title>
</head>
<body align= "center" >
<h2> CREATE YOUR ACCOUNT</h2>
<table cellspacing= "2" align= "center" cellpadding= "4" border= "0">
<tr><td> Name</td>
<td><input type= "text" placeholder= "Enter your name" id= "n1"></td></tr>
<tr><td>Email </td>
<td><input type= "text" placeholder="Enter your email id" id= "e1"></td></tr>
<tr><td> Set Password</td>
<td><input type="password" placeholder= "Set a password" id= "p1"></td></tr>
<tr><td>Confirm Password</td>
<td><input type="password" placeholder="Confirm your password" id="p2"></td></tr>
<tr><td>
<input type="submit" value="Create" onClick="create_account()"/>
</table>
<script type= "text/javascript">
function create_account(){
var n=document.getElementById("n1").value;
var e=document.getElementById("e1").value;
var p=document.getElementById("p1").value;
var cp=document.getElementById("p2").value;
//Code for password validation
var letters = /^[A-Za-z]+$/;
var email_val = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
//other validations required code
if(n==''||e==''||p==''||cp==''){
alert("Enter each details correctly");
}
else if(!letters.test(n))
{
alert("Name is incorrect must contain alphabets only");
}
else if (!email_val.test(e))
{
alert("Invalid email format please enter valid email id");
}
else if(p!=cp)
{
alert("Passwords not matching");
}
else if(document.getElementById("p1").value.length > 12)
{
alert("Password maximum length is 12");
}
else if(document.getElementById("p1").value.length < 6)
{
alert("Password minimum length is 6");
}
else{
alert("Your account has been created successfully... Redirecting to youtube.com");
window.location="https://youtube.com/";
} } </script> </body></html>
14
PHP
Server Side Scripting using PHP
PHP is a server side scripting language used to create dynamic web pages. PHP stands for Hypertext Preprocessor. It is an
interpreted language. It is embedded in HTML. It is an open source language. PHP supports different databases hence large
scale websites are developed using PHP.
PHP Features
PHP is very popular language because of its simplicity and open source. There are some important features of PHP given
below:
Performance: PHP script is executed much faster than those scripts which are written in other languages such as JSP and ASP.
PHP uses its own memory, so the server workload and loading time is automatically reduced, which results in faster
processing speed and better performance.
Open Source: PHP source code and software are freely available on the web. You can develop all the versions of PHP
according to your requirement without paying any cost. All its components are free to download and use.
Familiarity with syntax: PHP has easily understandable syntax. Programmers are comfortable coding with it
Embedded: PHP code can be easily embedded within HTML tags and script.
Platform Independent: PHP is available for WINDOWS, MAC, LINUX& UNIX operating system. A PHP application developed in
one OS can be easily executed in other OS also.
Database Support: PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g.,
E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language: PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the
time of execution based on the type of data it contains on its value.
Web servers Support: PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS, etc
Security: PHP is a secure language to develop the website. It consists of multiple layers of security to prevent threads and
malicious attacks.
Control: Different programming languages require long script or code, whereas PHP can do the same work in a few lines of
code. It has maximum control over the websites like you can make changes easily whenever you want.
A Helpful PHP Community:It has a large community of developers who regularly updates documentation, tutorials, online
help, and FAQs. Learning PHP from the communities is one of the significant benefits.
Basic PHP syntax
A PHP script can be placed anywhere in the document. A PHP script starts with
• The default file extension for PHP files is “.php”
• A PHP file normally contains HTML tags, and some PHP scripting code
• PHP statements are terminated by semicolon (;)
• In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are not case-sensitive
A PHP script starts with <?php and ends with ?>:
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 First PHP” on a web page:
<!DOCTYPE> <html> <body> <?php
echo “<h2>Hello First PHP</h2>”;
?> </body> </html>
PHP Data types
PHP data types are used to hold different types of data or
values. PHP supports 8 primitive data types that can be
categorized further in 3 types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types
15
PHP Data Types: Scalar Types decimal point, including a negative or positive sign.
It holds only single value. There are 4 scalar data types in Example:
PHP. <?php
1. Boolean $n1 = 19.34;
2. integer $n2 = 54.472;
3. float $sum = $n1 + $n2;
4. string echo “Addition of floating numbers:” .$sum;
PHP Data Types: Compound Types ?>
It can hold multiple values. There are 2 compound data Output:
types in PHP. Addition of floating numbers: 73.812
1. array
2. object PHP String
PHP Data Types: Special Types A string is a non-numeric data type. It holds letters or any
There are 2 special data types in PHP. alphabets, numbers, and even special characters.
1. resource String values must be enclosed either within single quotes
2. NULL or in double quotes. But both are treated differently. To
clarify this, see the example below: Example:
PHP Boolean <?php
Booleans are the simplest data type works like switch. It $company = “Java”;
holds only two values: TRUE (1) or FALSE (0). It is often //both single and double quote statements will treat
used with conditional statements. If the condition is different
correct, it returns TRUE otherwise FALSE. Example: echo “Hello $company”;
<?php echo “</br>”;
if (TRUE) echo “This condition is TRUE.”; if (FALSE) echo ‘Hello $company’;
echo “This condition is FALSE.”; ?>
?> Output: Output:
This condition is TRUE. Hello Java
Hello $company
PHP Integer PHP Array
Integer means numeric data with a negative or positive An array is a compound data type. It can store multiple
sign. It holds only whole numbers, i.e., numbers without values of same data type in a single variable. Example:
fractional part or decimal points. <?php
Rules for integer: $bikes = array (“Royal Enfield”, “Yamaha”, “KTM”);
An integer can be either positive or negative. var_dump($bikes); //the var_dump() function returns the
An integer must not contain decimal point. datatype and values
Integer can be decimal (base 10), octal (base 8), or echo “</br>”;
hexadecimal (base 16). echo “Array Element1: $bikes[0] </br>”;
The range of an integer must be lie between echo “Array Element2: $bikes[1] </br>”; echo “Array
2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31. Element3: $bikes[2] </br>”;
Example: ?>
<?php Output:
$dec1 = 34; array(3) { [0]=> string(13) “Royal Enfield” [1]=> string(6)
$oct1 = 0243; “Yamaha” [2]=> string(3) “KTM” } Array Element1: Royal
$hexa1 = 0x45; Enfield
echo “Decimal number:” .$dec1. “</br>”; echo “Octal Array Element2: Yamaha
number:” .$oct1. “</br>”; echo “HexaDecimal number:” Array Element3: KTM
.$hexa1. “</br>”; ?>
PHP Float
A floating-point number is a number with a decimal point.
Unlike integer, it can hold numbers with a fractional or
16
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly declared.
Output:
Bike Model: Royal Enfield
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to external
PHP resources. For example - a database call. It is an external resource. This is an advanced topic of PHP, so we will discuss it
later in detail with examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is case
sensitive.
The special type of data type NULL defined a variable with no value. Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Operators (Arithmetic, logical, comparison, operator precedence)
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to perform
operations on variables or values. For example:
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction, etc. with
numeric values.
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison operators are
given:
17
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the evaluation and
manipulation of specific bits within the integer.
As PHP is a loosely typed language, so we do not need to declare the data types of the variables.
It automatically analyzes the values and makes conversions to its correct datatype.
A variable must start with a dollar ($) sign, followed by the variable name.
It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
A variable name must start with a letter or underscore (_) character.
A PHP variable name cannot contain spaces.
One thing to be kept in mind that the variable name cannot start with a number or special symbols.
PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
18
return ($number * factorial($number-1));
}}
Write a program to print 2 php variables using single echo factorial(4);
echo statement. ?>
<?php
Write a program to print “Hello World” using echo only?
$message_1 = “Good Morning.”; <?php
$message_2 = “Have a nice day!”; echo “Hello World”; ?>
echo $message_1.” “. $message_2; ?>
Write a program to print “Welcome to the PHP World”
Write a program to show days of the week . using some part of the text in variable & some part
<?php directly in echo.
<?php
$day = “7”;
$message = “Welcome to the PHP World”;
switch ($day) {
echo $message; ?>
case “1”:
echo “It is Monday!”; Write a program to check student grade based on the
break; marks using if-else statement.
case “2”: Conditions:
echo “It is today!”; If marks are 60% or more, grade will be First Division.
break; If marks between 45% to 59%, grade will be 2nd division.
case “3”: If marks between 33% to 44%, grade will be Third Division.
echo “It is Wednesday!”; If marks are less than 33%, student will be Fail.
break; <?php
case “4”: $marks = 80;
echo “It is Thursday!”; if ($marks>=60)
break; { $grade = “First Division”;}
case “5”: else if($marks>=45){
echo “It is Friday!”; $grade = “Second Division”;}
break; else if($marks>=33){
case “6”: $grade = “Third Division”;}
echo “It is Saturday!”; else{
break; case “7”: $grade = “Fail”; }
echo “It is Sunday!”; echo “Student grade: $grade”; ?>
break; Output
default: Student grade: First Division
echo “Invalid number!”;
Write a program to calculate factorial of a number using
}
for loop in php.
?>
<?php
$num = 4; $factorial = 1;
Write a PHP program to find factorial of a number using
for ($x=$num; $x>=1; $x--){
recursive function.
$factorial = $factorial * $x;}
<?php
echo “The factorial of $num is $factorial”;?>
function factorial($number) {
if ($number < 2) { Output
return 1; } The factorial of 4 is 24
else {
19
SQL
Structured Query Language SQL is the acronym for Structured Query Language. SQL is the standard language for
communicating with relational database management systems. SQL is used to query, insert, update and modify data.
Some common relational database management systems that use SQL are: Oracle, Sybase, MS SQL Server, MS Access,
MySQL, etc. SQL Command SQL defines following ways to manipulate data stored in an RDBMS.
DDL: Data Definition Language Data Definition Language includes changes to the structure of the table like creation of
table, altering table, deleting a table etc. All DDL commands are auto-committed. That means it saves all the changes
permanently in the database.
Command Description
create to create new table or database
alter for alteration
truncate delete data from table
drop to drop a table
rename to rename a table
DML: Data Manipulation Language DML commands are used for manipulating the data stored in the table and not the
table itself. DML commands are not auto-committed. It means changes are not permanent to database, they can be
rolled back.
Command Description
insert to insert a new row
update to update existing row
delete to delete a row
merge merging two rows or two tables
DCL: Data Control Language Data control language are the commands to grant and take back authority from any
database user.
Command Description
20