Unit 2 Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

UNIT II CLIENT SIDE PROGRAMMING 9

Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and Objects,-Regular


Expressions- Exception Handling-Validation-Built-in objects-Event Handling- DHTML with JavaScript-
JSON introduction – Syntax – Function Files – Http Request – SQL.

Java Script: An introduction to JavaScript


It is an object-oriented computer programming language commonly used to create interactive
effects within web browsers.
JavaScript is the programming language of HTML and the Web.
It introduces the dynamic behavior of the web pages to react for event occurrence.
JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

This example uses the method to "find" an HTML element (with id="demo") and changes the
element content (innerHTML) to "Hello JavaScript":

Example
<!DOCTYPE html>
<html>

<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h1>A Web Page</h1>


<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

JavaScript Can Change HTML Elements Styles


Hiding HTML elements can be done by changing the display style:

Example
document.getElementById("demo").style.display = "none";

Showing hidden HTML elements can also be done by changing the display style:

Example
document.getElementById("demo").style.display = "block";

JavaScript Where To
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

External JavaScript

Scripts can also be placed in external files:

External file: myScript.js


function myFunction() {
 document.getElementById("demo").innerHTML = "Paragraph changed.";
}

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of
a <script> tag:

Example
<script src="myScript.js"></script>

You can place an external script reference in <head> or <body> as you like.


The script will behave as if it was located exactly where the <script> tag is located.

External scripts cannot contain <script> tags.

JavaScript DOM Model


What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style
of a document."

The W3C DOM standard is separated into 3 different parts:

 Core DOM - standard model for all document types


 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:

 The HTML elements as objects


 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.

The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects


With the object model, JavaScript gets all the power it needs to create dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

JavaScript - HTML DOM Method

HTML DOM methods are actions you can perform (on HTML Elements).

HTML DOM properties are values (of HTML Elements) that you can set or change.

The HTML DOM Document Object

The document object represents your web page.

If you want to access any element in an HTML page, you always start with accessing the
document object.

Below are some examples of how you can use the document object to access and manipulate
HTML.

Finding HTML Elements


Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements

Property Description

element.innerHTML =  new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML


element

element.style.property = new style Change the style of an HTML element

Method Description

element.setAttribute(attribute, value) Change the attribute value of an HTML


element
Adding and Deleting Elements

Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream

Creating and Adding Element using Java Script


HTML Body Section
<div id="form_sample"></div>
Java Script Section
var x = document.getElementById("form_sample");
var cf = document.createElement('form'); // Create New Element Form
cf.setAttribute("action", ""); // Setting Action Attribute on Form
cf.setAttribute("method", "post"); // Setting Method Attribute on Form
cf.setAttribute("id", "frm1"); // Setting Method Attribute on Form
x.appendChild(cf); // Appending the element to parent tag
document.getElementById("frm1").submit(); // Submitting the form
Removing and Appending Element using Java Script
<!DOCTYPE html>
<html>
<body>

<div id="myDIV">
<span id="mySpan1" style="font-size:35px;">A Span element 1</span>
<span id="mySpan2" style="font-size:35px;">A Span element 2</span>
</div>

<button onclick="removeEle()">Remove span</button>


<button onclick="appendEle()">Insert span</button>

<script>
var c = document.getElementById("mySpan1");

function removeEle() {
c.parentNode.removeChild(c);
}

function appendEle() {
var d = document.getElementsByTagName("DIV")[0]
d.appendChild(c);
}
</script>

</body>
</html>
Creating and Replacing Element using Java Script
<!DOCTYPE html>
<html>
<body>

<div id = "div1">
This is first paragraph
</div>

<div id = "div2"><p>This is second Paragraph</p></div>

<button onclick="replace()">create</button>

<script>

function replace() {
var ce = document.createElement("p");
ce.setAttribute("id", "p1");
ce.innerHTML = "New Paragraph Content";
var p = document.getElementsByTagName("div")[1].childNodes[0];
document.getElementsByTagName("div")[1].replaceChild(ce, p);
// document.getElementById("p1").innerHTML = "New Paragraph Content";
}
</script>

</body>
</html>
Adding Events Handlers

Method Description

document.getElementById(id).onclick = Adding event handler code to an onclick event


function(){code}

Changing HTML Style

To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style

The following example changes the style of a <p> element:

Example
<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

RegExp Object

A regular expression is an object that describes a pattern of characters.

Regular expressions are used to perform pattern-matching and "search-and-replace" functions


on text.
Syntax
/pattern/modifiers;
Example
var patt = /w3schools/i

Example explained:

 /w3schools/i  is a regular expression.


 w3schools  is a pattern (to be used in a search).
 i  is a modifier (modifies the search to be case-insensitive).

For a tutorial about Regular Expressions, read our JavaScript RegExp Tutorial.

Modifiers

Modifiers are used to perform case-insensitive and global searches:

Modifier Description

g Perform a global match (find all matches rather than stopping after the first matc

i Perform case-insensitive matching

m Perform multiline matching

Brackets

Brackets are used to find a range of characters:

Expression Description
[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-digit)

(x|y) Find any of the alternatives specified

Metacharacters

Metacharacters are characters with a special meaning:

Metacharacter Description

. Find a single character, except newline or line terminator

\w Find a word character

\W Find a non-word character

\d Find a digit
\D Find a non-digit character

\s Find a whitespace character

\S Find a non-whitespace character

\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like th

\B Find a match, but not at the beginning/end of a word

\0 Find a NUL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character


\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal number dd

\udddd Find the Unicode character specified by a hexadecimal number dddd

Quantifiers

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

n{X} Matches any string that contains a sequence of X n's

n{X,Y} Matches any string that contains a sequence of X to Y n's

n{X,} Matches any string that contains a sequence of at least X n's

n$ Matches any string with n at the end of it


^n Matches any string with n at the beginning of it

?=n Matches any string that is followed by a specific string n

?!n Matches any string that is not followed by a specific string n

Exception Handling

The try statement lets you test a block of code for errors.

The catch statement lets you handle the error.

The throw statement lets you create custom errors.

The finally statement lets you execute code, after try and catch, regardless of the result.

Errors Will Happen!

When executing JavaScript code, different errors can occur.

Errors can be coding errors made by the programmer, errors due to wrong input, and other
unforeseeable things.

Example
function myFunction() {
  var message, x;
  message = document.getElementById("p01");
  message.innerHTML = "";
  x = document.getElementById("demo").value;
  try {
    if(x == "") throw "is empty";
    if(isNaN(x)) throw "is not a number";
    x = Number(x);
    if(x > 10) throw "is too high";
    if(x < 5) throw "is too low";
  }
  catch(err) {
    message.innerHTML = "Error: " + err + ".";
  }
  finally {
    document.getElementById("demo").value = "";
  }
}

JavaScript Form Validation

HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the
form from being submitted:

<!DOCTYPE html>
<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.php" onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

JavaScript Can Validate Numeric Input


<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Can Validate Input</h2>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;

// If x is Not a Number or less than one or greater than 10


if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Automatic HTML Form Validation

HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form from being submitted:

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>

</body>
</html>

Built-in Objects

 Built-in objects are not related to any Window or DOM object model.
 These objects are used for simple data processing in the JavaScript.

1. Math Object

 Math object is a built-in static object.


 It is used for performing complex math operations.
Math Properties

Math Property Description

SQRT2 Returns square root of 2.

PI Returns Π value.

E\ Returns Euler's Constant.

LN2 Returns natural logarithm of 2.

LN10 Returns natural logarithm of 10.

LOG2E Returns base 2 logarithm of E.

LOG10E Returns 10 logarithm of E.


Math Methods

Methods Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns cosine of a number.

floor() Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is base exponent.

Example: Simple Program on Math Object Methods

<html>
     <head>
          <title>JavaScript Math Object Methods</title>
     </head>
     <body>
          <script type="text/javascript">
         
               var value = Math.abs(20);
               document.write("ABS Test Value : " + value +"<br>");
         
               var value = Math.acos(-1);
               document.write("ACOS Test Value : " + value +"<br>");
         
               var value = Math.asin(1);
               document.write("ASIN Test Value : " + value +"<br>");
         
               var value = Math.atan(.5);
               document.write("ATAN Test Value : " + value +"<br>");
          </script>
     </body>
</html>

Output

ABS Test Value : 20


ACOS Test Value : 3.141592653589793
ASIN Test Value : 1.5707963267948966
ATAN Test Value : 0.4636476090008061

Example: Simple Program on Math Object Properties

<html>
     <head>
          <title>JavaScript Math Object Properties</title>
     </head>
     <body>
          <script type="text/javascript">
               var value1 = Math.E
               document.write("E Value is :" + value1 + "<br>");
         
               var value2 = Math.LN2
               document.write("LN2 Value is :" + value2 + "<br>");
         
               var value3 = Math.LN10
               document.write("LN10 Value is :" + value3 + "<br>");
         
               var value4 = Math.PI
               document.write("PI Value is :" + value4 + "<br>");
          </script>
     </body>
</html>

Output:

E Value is :2.718281828459045
LN2 Value is :0.6931471805599453
LN10 Value is :2.302585092994046
PI Value is :3.141592653589793

2. Date Object

 Date is a data type.


 Date object manipulates date and time.
 Date() constructor takes no arguments.
 Date object allows you to get and set the year, month, day, hour, minute, second and
millisecond fields.
Syntax:
var variable_name = new Date();

Example:
var current_date = new Date();

Date Methods

Methods Description

Date() Returns current date and time.

getDate() Returns the day of the month.

getDay() Returns the day of the week.

getFullYear() Returns the year.

getHours() Returns the hour.


getMinutes() Returns the minutes.

getSeconds() Returns the seconds.

getMilliseconds() Returns the milliseconds.

getTime() Returns the number of milliseconds since January 1, 1970 at 12:00


AM.

getTimezoneOffset() Returns the timezone offset in minutes for the current locale.

getMonth() Returns the month.

setDate() Sets the day of the month.

setFullYear() Sets the full year.

setHours() Sets the hours.

setMinutes() Sets the minutes.

setSeconds() Sets the seconds.

setMilliseconds() Sets the milliseconds.

setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.

setMonth() Sets the month.

toDateString() Returns the date portion of the Date as a human-readable string.

toLocaleString() Returns the Date object as a string.

toGMTString() Returns the Date object as a string in GMT timezone.

valueOf() Returns the primitive value of a Date object.


Example : JavaScript Date() Methods Program

<html>
     <body>
     <center>
          <h2>Date Methods</h2>
          <script type="text/javascript">
               var d = new Date();
               document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
               document.write("<b>Hours:</b> " + d.getHours()+"<br>");
               document.write("<b>Day:</b> " + d.getDay()+"<br>");
               document.write("<b>Month:</b> " + d.getMonth()+"<br>");
               document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
               document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
          </script>
     </center>
     </body>
</html>

Output:

3. String Object

 String objects are used to work with text.


 It works with a series of characters.
Syntax:
var variable_name = new String(string);

Example:
var s = new String(string);

String Properties

Properties Description

length It returns the length of the string.

prototype It allows you to add properties and methods to an object.

constructor It returns the reference to the String function that created the object.

String Methods

Methods Description

charAt() It returns the character at the specified index.

charCodeAt() It returns the ASCII code of the character at the specified position.

concat() It combines the text of two strings and returns a new string.

indexOf() It returns the index within the calling String object.

match() It is used to match a regular expression against a string.

replace() It is used to replace the matched substring with a new substring.

search() It executes the search for a match between a regular expression.

slice() It extracts a session of a string and returns a new string.

split() It splits a string object into an array of strings by separating the string into the
substrings.

toLowerCase() It returns the calling string value converted lower case.


toUpperCase() Returns the calling string value converted to uppercase.

Example : JavaScript String() Methods Program

<html>
     <body>
     <center>
          <script type="text/javascript">
               var str = "CareerRide Info";
               var s = str.split();
               document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
               document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
               document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
               document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
               document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
          </script>
     <center>
     </body>
</html>

Output:

Common Built-in Functions

Functions Description
isNan() Returns true, if the object is Not a Number.
Returns false, if the object is a number.
parseFloat If the string begins with a number, the function reads through the string until it finds
(string) the end of the number; cuts off the remainder of the string and returns the result.
If the string does not begin with a number, the function returns NaN.
parseInt (string) If the string begins with an integer, the function reads through the string until it
finds the end of the integer, cuts off the remainder of the string and returns the
result.
If the string does not begin with an integer, the function returns NaN (Not a
Number).
String (object) Converts the object into a string.
eval() Returns the result of evaluating an arithmetic expression.

JavaScript Events

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:


<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?
</button>

In the example above, the JavaScript code changes the content of the element with id="demo".

In the next example, the code changes the content of its own element (using this.innerHTML):

Example
<button onclick="this.innerHTML = Date()">The time is?</button>

JavaScript code is often several lines long. It is more common to see event attributes calling
functions:

Example
<button onclick="displayDate()">The time is?</button>
Common HTML Events

Here is a list of some common HTML events:

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 the page

onchange The attribute will work with elements like text box and select box.

DHTML JavaScript

DHTML stands for Dynamic HTML. Dynamic means that the content of the web page can be
customized or changed according to user inputs i.e. a page that is interactive with the user.

To integrate JavaScript into HTML, a Document Object Model(DOM) is made for the HTML
document. In DOM, the document is represented as nodes and objects which are accessed by
different languages like JavaScript to manipulate the document.

Example to understand how to use JavaScript in DHTML.

<html>
    <head>
        <title>DOM programming</title>
    </head>
      
    <body>
        <h1>GeeksforGeeks</h1>
        <p id = "geeks">Hello Geeks!</p>
        <script style = "text/javascript">
        document.getElementById("geeks").innerHTML = 
              "A computer science portal for geeks";
        </script>
    </body>
</html>
                    
Output:

JSON - Introduction

JSON: JavaScript Object Notation.

JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.

Exchanging Data

When exchanging data between a browser and a server, the data can only be text.

JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

We can also convert any JSON received from the server into JavaScript objects.

This way we can work with the data as JavaScript objects, with no complicated parsing and
translations.

Sending Data

If you have data stored in a JavaScript object, you can convert the object into JSON, and send it
to a server:

Example
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;

You will learn more about the JSON.stringify() function later in this tutorial.

Receiving Data

If you receive data in JSON format, you can convert it into a JavaScript object:
Example
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;

You will learn more about the JSON.parse() function later in this tutorial.

Storing Data

When storing data, the data has to be a certain format, and regardless of where you choose to
store it, text is always one of the legal formats.

JSON makes it possible to store JavaScript objects as text.

Example

Storing data in local storage

// Storing data:
myObj = {name: "John", age: 31, city: "New York"};
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
Function Files & Http Request
A common use of JSON is to read data from a web server, and display the data in a web page.
<!DOCTYPE html>
<html>
<body>

<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].display + "</br>";
}
document.getElementById("id01").innerHTML = out;
}
</script>

</body>
</html>

Output
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
jQuery Tutorial
SQL Tutorial
PHP Tutorial
XML Tutorial

JSON SQL
Customers.html
<!DOCTYPE html>
<html>
<body>

<h1>Customers</h1>
<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://www.w3schools.com/js/customers_mysql.php";

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myFunction(this.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) {
    var arr = JSON.parse(response);
    var i;
    var out = "<table>";

    for(i = 0; i < arr.length; i++) {


        out += "<tr><td>" +
        arr[i].Name +
        "</td><td>" +
        arr[i].City +
        "</td><td>" +
        arr[i].Country +
        "</td></tr>";
    }
    out += "</table>";
    document.getElementById("id01").innerHTML = out;
}
</script>

</body>
</html>

The PHP Code on the Server

This is the PHP code running on the server:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");

$result = $conn->query("SELECT CompanyName, City, Country FROM Customers");

$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "[") {$outp .= ",";}
    $outp .= '{"Name":"'  . $rs["CompanyName"] . '",';
    $outp .= '"City":"'   . $rs["City"]        . '",';
    $outp .= '"Country":"'. $rs["Country"]     . '"}';
}
$outp .="]";

$conn->close();

echo($outp);
?>

You might also like