Unit 02 - Full Stack Web Development
Unit 02 - Full Stack Web Development
Development
by Dr Piyush Bagla
JavaScript
• Inline JavaScript
• Internal JavaScript
• External JavaScript
<script src="script.js"></script>
Common ways to select HTML element
• getElementById()
• getElementsByClassName()
• getElementsByName()
• getElementsByTagName()
JavaScript Variables
Variables can
be declared in
4 ways:
• ES6 introduced the two new JavaScript keywords: let and const.
• Variables declared with the var always have Global Scope or Function Scope.
• Variables declared with the var keyword can NOT have block scope.
• Variables declared with var inside a { } block can be accessed from outside the block.
Introduced
var a; // allowed
let b; // allowed
const c = 10 ; // allowed
Initialization
const c;
c = 30; // not allowed
SyntaxError: Missing initializer in const declaration
Redeclaration
var a = 10;
var a = 20; //its possible to with var
let b = 10;
let b = 20; //its not possible with let
SyntaxError: Identifier 'b' has already been declared
const c = 10;
const c = 20; //its not possible with const
SyntaxError: Identifier 'c' has already been declared
Redeclaring Var
• Variables defined with var can be • If you re-declare a JavaScript variable
redeclared. declared with var, it will not lose its value.
var a = 5;
• Redeclaring a variable using var a; // var is still 5
the var keyword can impose problems.
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Reinitialization
Output:
Hello, foofi!
Hello, foofi!
Scope
a) Functional Scope: declare greeting variable with var now
function wishFoofi() {
var greeting = "Hello, foofi!"; //greeting remained functional scoped
console.log(greeting);
}
Output:
Hello, foofi!
ReferenceError: greeting is not defined
Scope
{
var x = 10;
b) Block Scope }
console.log(x); // output 10
{
let y = 20;
}
console.log(y); // output : ReferenceError: y is not defined
{
const z = 30;
}
console.log(z); // output : ReferenceError: z is not defined
Hoisted
* variables with let and const are also hoisted but at the top of block scope and
they are not assigned with undefined.
JavaScript Datatypes
In JavaScript:
• var, let, and const are not data types themselves; they are keywords
used for variable declaration.
• Data types in JavaScript are the types of values that variables can hold,
such as numbers, strings, booleans, objects, arrays, etc.
• When you write something like var a = 10;, a can hold a number value (10
in this case), so we say that a is a variable holding a numeric literal.
• In summary, while in C and C++, we explicitly specify the data type of a
variable when declaring it, in JavaScript, we declare variables using
keywords like var, let, or const, and the data type of a variable is
determined by the value it holds.
JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
JavaScript Data 6.
7.
Null
Symbol
8. Object
Types
The Object Datatype
1. Alert Box
2. Confirm Box
3. Prompt Box
JavaScript Form Validation
1.HTML Validation: HTML5 introduced several built-in validation attributes for form inputs such
as required, min, max, pattern, etc.
2.JavaScript Validation: You can use JavaScript to implement custom validation logic beyond
what HTML provides. This allows you to perform complex validation tasks, such as validating
the format of input data, checking for uniqueness, or interacting with external data sources for
validation.
3.CSS Role: While CSS itself cannot perform form validation, it can be used to enhance the
visual feedback of validation errors. For example, you can style invalid form inputs using the
:invalid and :valid pseudo-classes to provide visual cues to users.
Regular Expression
Regular expressions in JavaScript, also known as regex or regexp, are a sequence of characters that
form a search pattern.
Example:
Regular expressions support modifiers that affect how a pattern is matched, such as:
1. i: Case-insensitive match
2. g: Global match (find all matches, not just the first)
3. m: Multiline match
Example:
Replace
str.replace(/apple/i, ”GEHU");
Regular Expression Patterns
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
DOM – Document Object Model
• The DOM is a W3C (World Wide Web Consortium) standard.
• It defines the logical structure of documents and how a document is accessed and
manipulated.
• When a web page is loaded, the browser creates a Document Object Model of the
page.
HTML DOM
Note:
window object represents the browser window and provides browser-related functionality such as navigating to URLs
(window.location), managing browser history (window.history), setting timeouts (window.setTimeout), and more.,
the document object represents the HTML document loaded in that window and allows manipulation of its content.
Manipulation Using DOM
<body>
<button id="myButton">Click Me</button>
<script>
let button = document.getElementById("myButton");
// Add a click event listener
button.addEventListener("click", function () {
alert("Button was clicked!");
});
// Manually trigger a click event
function triggerClick() {
let event = new Event("click"); // Create a standard click event
button.dispatchEvent(event); // Dispatch the event
}
// Simulate a click after 3 seconds
setTimeout(triggerClick, 3000);
</script>
</body>
JavaScript can create new HTML events on the page
2. Creating and Dispatching Custom Events
•Use the CustomEvent constructor to create events with additional data.
•Use dispatchEvent() to trigger the event.
<script>
// Step 1: Create an event listener for the custom event
document.addEventListener("myCustomEvent", function(event) {
document.getElementById("message").textContent = event.detail.message;
});
JavaScript JQuery
document.getElementById("id"); $("#id");
Syntax
$(document).ready(function(){
});
OR
$(function(){
});
Get Methods
• text()
• html()
• attr()
• val()
Set Methods
• text()
• html()
• attr()
• val()
AJAX
• AJAX is the art of exchanging data with a server and updating parts of a web
page - without reloading the whole page.
• Examples of applications using AJAX are Gmail, Google Maps, YouTube, and
Facebook tabs.
• With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from
a remote server using both HTTP Get and HTTP Post - And you can load the
external data directly into the selected HTML elements of your web page!
Note:
1 2
5
4
Ways to Implement AJAX in JavaScript
There are several ways to implement AJAX in JavaScript. Below are the main methods:
Syntax
Parameters:
$.get(URL,callback);
Parameters:
• The required URL parameter specifies the URL you wish to request.
• The optional callback parameter is the name of a function to be
executed if the request succeeds.
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$.get("data.html", function(response) {
$("#content").html(response); // Insert manually
});
});
});
</script>
post()
XML
$.post() is used to send data to the server using the HTTP POST method. Unlike $.get(), it is mainly used when
submitting forms, sending user input, or updating data on the server.
$.post(URL,data, callback);
Parameters:
• The required URL parameter specifies the URL you wish to request.
• Data (optional)– send additional data to the server along with the request.
• The optional callback parameter is the name of a function to be executed if the request
succeeds.
credit w3schools
post()
XML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$("#btn").click(function () {
$.post("server.php", { key: "value" }, function(response) {
$("#content").html(response); // Insert response manually
});
});
});
</script>
XML
credit w3schools
XML is Extensible
• We can add our own tags
• Most XML applications will work as expected even if new data is added (or removed).
<note>
<to>ABC</to>
<from type=‘abc’>XYZ</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>ABC</to>
<from>XYZ</from>
<body>Don't forget me this weekend!</body>
</note>
credit w3schools
XML Syntax Rules
• XML Documents Must Have a Root Element
• The XML Prolog
<?xml version="1.0" encoding="UTF-8"?>
The XML prolog is optional. If it exists, it must come first in the document.
credit w3schools
XML Syntax Rules
Entity References
• If you place a character like "<" inside an XML element, it will generate an error because the parser
interprets it as the start of a new element.
To avoid this error, replace the "<" character with an entity reference:
credit w3schools
Well Formed vs Valid XML Documents
❖ A "well formed" XML document is not the same as a "valid" XML document.
There are two different document type definitions that can be used with XML:
credit w3schools
DTD
DTD
A DTD defines the structure and the legal elements and attributes of an XML document.
Note.dtd
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE note
<!DOCTYPE note SYSTEM "Note.dtd"> [
<note> <!ELEMENT note (to,from,body)>
<!ELEMENT to (#PCDATA)>
<to>Tove</to> <!ELEMENT from (#PCDATA)>
<from>Jani</from> <!ELEMENT heading (#PCDATA)>
<heading>Reminder</heading> <!ELEMENT body (#PCDATA)>
<body>Don't forget me this weekend!</body> ]>
</note>
credit w3schools
XML
XMLSchema
Schema
An XML Schema describes the structure of an XML document, just like a DTD.
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
credit w3schools
Why XML Schemas are More Powerful than DTD?
credit w3schools
JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and
easy for machines to parse and generate. It's widely used for exchanging data between a server and a client, often in web
applications. {
"users": [
{
"id": 1,
"name": "John Doe",
"email": "[email protected]",
"hobbies": ["reading", "traveling"]
},
{
"id": 2,
"name": "Jane Smith",
"email": "[email protected]",
"hobbies": ["photography", "painting"]
},
]
}
XML vs JSON