JAVASCRIPT AND JSON

 CLIENT SIDE PROGRAMMING 

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. 

An introduction to JavaScript

  • JavaScript is an interpreted programming or script language
  • Invented in 1995 at Netscape Corporation
  • JavaScript programs are run by an interpreter built into the user's web browser (not on the server)
  • Client side scripting

What is JavaScript?

  • JavaScript was designed to add interactivity to HTML pages
  • JavaScript is a scripting language
  • A JavaScript consists of lines of executable computer code
  • A JavaScript is usually embedded directly into HTML pages
  • JavaScript is an interpreted language
  • Everyone can use JavaScript without purchasing a license

What can a JavaScript Do?

       JavaScript gives HTML designers a programming tool

       JavaScript can put dynamic text into an HTML page

       JavaScript can react to event

       JavaScript can read and write HTML elements

       JavaScript can be used to validate data

       JavaScript can be used to detect the visitor's browser

       JavaScript can be used to create cookies

Java vs. JavaScript

       Requires the JDK to create the applet

       Requires a Java virtual machine to run the applet

       Applet files are distinct from the XHTML code

       Source code is hidden from the user

       Programs must be saved as separate files and compiled before they can be run

       Programs run on the server side

Javascript

       Requires a text editor

       Required a browser that can interpret JavaScript code

       JavaScript can be placed within HTML and XHTML

       Source code is made accessible to the user

       Programs cannot write content to the hard disk

       Programs run on the client side

Event-driven programming

v  JavaScript programs wait for user actions called events and respond to them

v  Event-driven Programming: writing programs driven by user events

Syntax

       To embed a client-side script in a Web page, use the element:
<script>
               
script commands and comments
</script>

       To access an external script, use:
<script src=“url”>
                 
script commands and comments
</script>

<script>
                statement-1;
                statement-2;
                ….
                statement-n;
</script>

 

Where to Put the JavaScript

       <head> section

      Save file with extension .html

       <body> section

      Save file with extension .html

       External scripts

      Save file with extension .js

JavaScript in the <head> section

<html>
                <head>
                <title>Java Script Example</title>
                <script>
                                alert("Hello World!");
   </script>
                </head>
                <body>
  
                </body>
</html>

 

Scripts in the <body> section

<html>
                <head>
                                <title>Java Script Example</title>
                </head>
<body>
   <script>
                                alert("Hello World1");
   </script>
</body>
</html>

 

Using External JavaScript

extfile.js

alert("Hello");

alert (“Welcome to Javascript”);

alert (“Have a nice day!”);

 

test.html
<html>
                <head>
   <script src=“extfile.js">
   </script>
                </head>
                <body>
                </body>
</html>

 

Comments

       The syntax for a single-line comment is:

                // comment text

       The syntax of a multi-line comment is:

                /*
               
comment text covering several lines
               
*/

Writing Output to a Web Page

       JavaScript displays data in the following ways:

                document.write() or      document.writeln()

                window.alert() or alert()

                innerHTML

Variables

JavaScript supports Four different types of variables:

      Numeric variables can be a number

                13, 22.5, or -3.14159

      String variables is any group of characters

                 “Hello” or “Happy Holidays!”

      Boolean variables are variables that accept one of two values

                true or false

      null variables is a variable that has no value at all

Declaring a Variable

       Declare a variable using the var keyword or by assigning the variable a value

       Any of the following commands is a legitimate way of creating a variable named “Month”:

var Month;

var Month = “December”;

Month = “December”;

var age=20;

 

Functions

       Syntax

                                function function-name()
                                {
                                                statement ;
                                                statement ;
                                                ...
                                                statement ;
                                }

       Example

<script>
function MyFunction()
{
                alert("Hello!");
                alert("How are you?");
}
</script>

JavaScript DOM Model

       What is DOM?

      The Document Object Model (DOM) is a programming API for HTML and XML documents.

      It defines the logical structure of documents and the way a document is accessed and manipulated.

      With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content

Nodes Organise the Page

<!DOCTYPE html>
<html>
<head>
      <title>My page</title>
</head>
<body>
  <p>This text is on my page</p>
</body>
</html>

What is a Node?

       Element Node – contains an HTML tag

       Text Node – contains text

      Text Nodes are contained in Element Nodes

 

DOM Methods

  • document.createElement()
  • document.createTextNode()
  • appendChild()
  • removeChild()
  • document.getElementById()
  • document.getElementsByTagName()
  • document.getElementsByClassName()
  • getAttribute()
  • setAttribute()
  • innerHTML 

Example: Adding Some Text to a Page

There are five steps:

1.       Create a new Element

2.       Create new Text

3.       Append the new Text to the new Element

Find an existing Element

5.       Append the new Element to the existing Element

1.       Create New Element Node

Create a new <p> tag (element) so that we can attach some text to it

Put the new object into a variable

                var newNode;

                newNode = document.createElement(“p”);

Create a Text Node

Put the new text node into a variable

                var newText;

                newText = document.createTextNode(“Some text”);

 Attach the New Text Node to the New Element

    To put the text into the page, we have to attach the text node to the new HTML element:

    new Node.appendChild(newText);

Find an Existing Element

    The new element with our text node attached to it is still floating around in a Javascript world. 

Assign this existing element to a variable

var docElement;

docElement = document.getElementById(“thisLocation”);

5.       Append the New Element to the Existing Element

To insert our text into the page, we now have to append the new element to the existing element

docElement.appendChild(newNode);

 

Putting the 5 Steps Together

<!DOCTYPE html>
<html>
<head>
<script>
var myText;
myText = "This is new text to be added to the page dynamically.";
function addText(location)
{
                var newNode;
                var newText;
                var docElement;
                newNode = document.createElement("p");
                newText = document.createTextNode(myText);
                newNode.appendChild(newText);
                docElement = document.getElementById(location);
                docElement.appendChild(newNode);
}
</script>
</head>
<body>
<p>
<a href="#" onclick="addText('thisLocation');">Click to add new text to the page</a></p>
<p id="thisLocation">New text will appear below here</p>
<p>Some further text in the page</p>
</body>
</html> 

Built in Objects

  • Array
  • Date
  • Math
  • String
  • RegExp
  • Number
  • Boolean

Array Object
  • Multiple values are stored in a single variable using the Array object.
  • In JavaScript, an array can hold different types of data types in a single slot, which implies that an array can have a string, a number or an object in a single slot.
  • An Array object can be created by using following ways:
    • Using the Array Constructor
    • Using the Array Literal Notation

Using the Array Constructor:

  • To create empty array when don’t know the exact number of elements to be inserted in an array
var arrayname = new Array(); 
  • To create an array of given size
var arrayname = new Array(size); 
  • To create an array with given elements
var arrayname = new Array(“element 1”,”element 2”,……..,”element n”);

Using the Array Literal Notation:

  • To create empty array
var arrayname =[ ]; 
  • To create an array when elements are given
var arrayname =[“element 1”,”element 2”,……..,”element n”];

Properties of the Array object

  • length - Returns the number of elements in the array
  • Constructor - Returns the function that created the Array object
  • Prototype - Add properties and methods to an object

Methods of the Array object

  • reverse() - Reverses the array elements
  • concat() - Joins two or more arrays
  • sort() - Sort the elements of an array
  • push() - Appends one or more elements at the end of an array
  • pop() - Removes and returns the last element
  • shift() - Removes and returns the first element
Math Object
  • The JavaScript Math object is used to perform mathematical tasks.
  • The Math object is a static built-in object, so no need to instantiate it, all its properties and methods can be accessed directly.

Exception Handling

  • Run time errors are exceptions and this exception is correct by the help of the try and catch method
Syntax:
        <script> 
          try 
          { 
            // Here the main Code run  
          }  
         catch ( exception e )  
          { 
             // The code will run when there is an exception  
           }  
        </script> 

Event Handling
  • Events are actions or occurrences that happen in the system, which the system tells you about so you can respond to them in some way if desired
  • Javascript has events to provide a dynamic interface to a webpage
  • These events are hooked to elements in the Document Object Model(DOM)
  • For example, if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box

Event Handler

  • It is a function that’s called when an event occurs to respond to any event
  • multiple handlers for the same event can be registered, and they will all be called when that event happens.
  • JavaScript offer three ways to register an event handler:
    • Inline event handlers
    • DOM on-event handlers
    • Using addEventListener()

DHTML

  • Dynamic HyerText Markup Language (DHTML) is a combination of Web development technologies used to create dynamically changing websites.
  • Web pages may include animation, dynamic menus and text effects.
  • HTML + JavaScript + CSS + DOM

Features

  • Dynamic content, which allows the user to dynamically change Web page content
  • Dynamic positioning of Web page elements
  • Dynamic style, which allows the user to change the Web page’s color, font, size or content

JSON

  • JavaScript Object Notation
  • An open standard file format, and data interchange format, 
  • Uses human-readable text to store and transmit data objects consisting of attribute–value pairs and array data types. 
  • It is a very common data format, with a diverse range of applications, such as serving as a replacement for XML in AJAX systems. 
  • JSON is commonly used to exchange information between web clients and web servers. 

Features

  • It is a lightweight data-interchange format
  • It is easy for humans to read and write
  • It is easy for machines to parse and generate
  • It is based on a subset of the JavaScript Programming Language Standard
  • JSON is a text format that is completely language independent
JSON is built on two structures:
  • A collection of name/value pairs. 
    • object, record, struct, dictionary, hash table, keyed list, or associative array
  • An ordered list of values.
    • array, vector, list, or sequence

JSON Syntax Rules

  • Data is in name/value pairs 
  • ":" to separate name from value
  • "," to separate name-value pairs
  • "{" and "}" for objects
  • "[" and "]" for arrays

Syntax:
{
"name" : "value“, 
"name" : "value“
}

JSON Object Example

  • A JSON object is a key-value data format that is typically rendered in curly braces.

  "color" : "Purple", 
  "id" : "210", 
  "composition" : {"R" : 70,"G" : 39,"B" : 89}
}

JSON Array Example

  • Data can also be nested within the JSON by using JavaScript arrays that are passed as a value using square brackets [ ] on either end of its array type.
{
    "colors" : 
    [
        { "color" : "Purple",  "id" : "210” },
        { "color" : "Blue", "id" : "211”},
        { "color" : "Black", "id" : "212” }
    ]
}

JSON Data Types 

JSON consist of 6 data types
  • simple data types
    • string
    • number
    • boolean
    • null/empty
  • complex data types
    • object
    • array

JSON Example


{
  "color" : "Purple“,
“id" : 210,
"visibility" : true,
  "popularity" : null
}

parse() Method:

  • JSON parse() method deserializes a JSON string representation to a JavaScript object
  • The parse() method takes the JSON string, as received from API response and converts it a JavaScript object

Example:
var jsonString = '{ "x": 5, "y": 6 }';
 var obj = JSON.parse( jsonString );  
 console.log(obj);

stringify() Method

  • The JSON.stringify() function converts a JavaScript value to a serialized JSON string.
  • In other words, JSON.stringify() returns a JSON string corresponding to a JavaScript object.

JSON Function Files

  • Create an array of objects in external js file
  • Create a JavaScript function with same name as external javascript file having array of json objects to display the array. 
  • Use an array literal as the argument
  • Add the external script
Example:

<!DOCTYPE html>
<html>
<body>
<div id="content"></div>
<script>
function myFunction(arr) 
{
  var out="";
  for(i = 0; i<arr.length; i++) 
  {
    out += arr[i].name +" "+ arr[i].department+"<br>";
  }
  document.getElementById("content").innerHTML = out;
}
</script>
<script src="myjson.js"></script>
</body>
</html>

myjson.js

myFunction([
{
"name": "Madan",
"department": "cse"
},
{
"name": "Suresh",
"department": "ece"
},
{
"name": "Muthu",
"department": "eee"
},
]);