Unit 2 (WD)
Unit 2 (WD)
What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
Asynchronous: AJAX can send and receive data in the background (asynchronously).
Partial Page Updates: Only a portion of the page is updated—no need to reload the full
webpage.
Fast and Smooth UX: AJAX makes web applications faster and more responsive.
Data Formats: Although "XML" is in the name, AJAX works with many formats like
JSON, HTML, Text, or XML.
Technology Role
HTML/XHTML For the structure of the page
CSS For styling the page
JavaScript To interact with the page and make AJAX requests
DOM For updating parts of the page dynamically
The object used in JavaScript to send/receive
XMLHttpRequest
requests
Server-Side Language (PHP, ASP.NET,
To process and return the data
etc.)
🔁 How AJAX Works (Step-by-Step Flow)
1. A user event (like clicking a button) occurs on the web page.
2. JavaScript creates an XMLHttpRequest object.
3. The request is sent to the web server (e.g., via PHP).
4. The server processes the request and sends back a response.
5. JavaScript receives the response and updates the webpage without reloading.
AJAX allows parts of a web page to update without reloading the entire page, which means:
Faster interactions
No flickering or full page reloads
Feels like a smooth, responsive app
🔁 Example: When you "like" a post on Instagram or Facebook, the like button updates instantly
without reloading the page—that's AJAX!
AJAX fetches only the required data, not the whole page.
📉 Example: Instead of reloading the full 2MB page, it might just request a 10KB JSON file.
✅ 3. Asynchronous Communication
You can keep interacting with the page while data is being fetched or submitted.
This avoids freezing or blocking the interface.
⚙️Example: While submitting a form, the user can continue browsing without interruption.
AJAX enables loading new data or components based on user action without a page refresh.
Example: Infinite scroll in Facebook, YouTube, or Instagram loads more posts automatically as
you scroll.
AJAX can:
AJAX is essential in building Single Page Applications (SPAs) like Gmail, Google Maps, or
Trello, where:
🧾 Example:
<student>
<name>John</name>
<age>22</age>
<course>Computer Science</course>
</student>
In AJAX:
🧾 Example:
{
"name": "John",
"age": 22,
"course": "Computer Science"
}
In AJAX:
You can receive a JSON response and convert it using JSON.parse() or automatically with
fetch().
fetch("data.json")
.then(response => response.json())
.then(data => {
console.log("Name:", data.name);
console.log("Age:", data.age);
});
What is JSON?
JSON (JavaScript Object Notation) is a format for storing and transporting data. It's often used when
data is sent from a server to a web page, or between APIs and applications.
✅ JSON Structure
{
"name": "John",
"age": 30,
"isStudent": false,
"hobbies": ["reading", "sports"],
"address": {
"city": "New York",
"zip": "10001"
}
}
✅ Access values
echo $array['name']; // Sam
echo $object->name; // Sam
🔸 Common Operations
Task JavaScript Python PHP
Parse JSON
JSON.parse() json.loads() json_decode()
string
file_put_contents() +
Write to file fs.writeFile (Node) json.dump()
json_encode()
<script>
$('#loadBtn').click(function() {
$('#content').load('about.html'); // Load HTML into div
});
</script>
</body>
</html>
✅ about.html
<h2>About Us</h2>
<p>We are passionate developers!</p>
🟡 When the user clicks the button, about.html is fetched and injected into the <div
id="content">.
Scenario
You have an XML file like this:
✅ books.xml
xml
CopyEdit
<books>
<book>
<title>JavaScript: The Good Parts</title>
<author>Douglas Crockford</author>
</book>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
</book>
</books>
You want to load this XML and display the book titles and authors on your web page.
<script>
function loadXML() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "books.xml", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const xml = xhr.responseXML;
const books = xml.getElementsByTagName("book");
let output = "<h2>Book List</h2><ul>";
output += "</ul>";
document.getElementById("bookList").innerHTML = output;
}
};
xhr.send();
}
</script>
</body>
</html>
Loading JSON with AJAX
<script>
function loadJSON() {
fetch("data.json")
.then(response => response.json())
.then(data => {
let output = "";
data.forEach(user => {
output += `<li>${user.name} - Age: ${user.age}</li>`;
});
document.getElementById("userList").innerHTML = output;
})
.catch(error => console.error("Error loading JSON:", error));
}
</script>
</body>
</html>
What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library.
DOM manipulation,
event handling,
AJAX calls,
and animations
<h2>Welcome to jQuery!</h2>
<p id="message">Click the button below:</p>
<script>
// jQuery code
$(document).ready(function() {
$("#myButton").click(function() {
$("#message").text("Hello! You clicked the button.");
});
});
</script>
</body>
</html>
🔍 Explanation
$(document).ready(): Makes sure the code runs after the page has fully loaded.
$("#myButton").click(): Adds a click event listener to the button.
$("#message").text(): Changes the text of the paragraph with ID message.
✅ What Happens?
When the page loads:
NEED OF JQUERY
You can do with one line in jQuery what might take several lines in plain JS.
👉 Example:
// Vanilla JS
document.getElementById("title").style.color = "blue";
// jQuery
$("#title").css("color", "blue");
2. Cross-Browser Compatibility
jQuery handles browser differences behind the scenes, so your code works the same in:
Chrome
Firefox
Safari
Edge
(and even old versions of IE)
5. Simplified AJAX
$.get("data.json", function(data) {
console.log(data);
});
$("#box").fadeIn();
$("#box").slideUp();
$("#btn").click(function() {
alert("Clicked!");
});
8. Chainability
$("#box").css("color", "red").slideUp().fadeIn();
✅ Basic Selectors
✅ Example:
<h1 id="mainHeading">Hello</h1>
<p class="info">Welcome!</p>
<p class="info">Enjoy your stay.</p>
$("#mainHeading").text("Hi there!"); // By ID
$(".info").css("color", "blue"); // By class
$("p").hide(); // All <p> tags
✅ Advanced Selectors
Selector Meaning
:first First matched element
:last Last matched element
:even, :odd Even/odd indexed elements
:eq(n) Specific index (starts at 0)
[attr=value] Attribute with specific value
input:checked Checked checkbox/radio
jQuery Selection Overview
In jQuery, selecting elements is extremely easy, and it's one of the reasons jQuery became so
popular. You can select elements using CSS-style selectors.
Where:
$("#myDiv").css("color", "blue");
$(".menu").show();
3. Tag Selector
9. :last
10. :eq(n)
Example:
<p id="para">This is a <b>paragraph</b> with <i>text</i>.</p>
javascript
CopyEdit
var text = $("#para").text();
console.log(text); // Output: "This is a paragraph with text."
Here, .text() returns the plain text, without the <b> and <i> tags.
Example:
<div id="content">
<p>This is a <b>bold</b> word.</p>
</div>
var htmlContent = $("#content").html();
console.log(htmlContent); // Output: "<p>This is a <b>bold</b> word.</p>"
Here, .html() includes the actual HTML tags (<p>, <b>), not just the text.
✅ 3. Getting Value of Form Elements (.val())
If you're working with form elements (like <input>, <textarea>, or <select>), you can use the
.val() method to get the current value of the element.
Here, .val() retrieves the value of the input field, not the text inside it.
Example:
<a id="link" href="https://example.com">Visit Example</a>
var hrefValue = $("#link").attr("href");
console.log(hrefValue); // Output: "https://example.com"
Here, .attr("href") retrieves the href attribute of the anchor <a> tag.
Example:
<div id="box" style="width: 100px; height: 100px; background-color:
red;"></div>
var width = $("#box").css("width");
console.log(width); // Output: "100px"
Example:
<p id="message">Old text</p>
<button id="changeText">Change Text</button>
<script>
$("#changeText").click(function() {
$("#message").text("New text!"); // Change the text of the <p>
});
</script>
When you click the button, the text inside the <p> element changes to "New text!".
Example:
<div id="content">Old <b>bold</b> text</div>
<button id="changeHTML">Change HTML</button>
<script>
$("#changeHTML").click(function() {
$("#content").html("<i>New italic text</i>"); // Update with new HTML
});
</script>
When you click the button, the content of the <div> changes to "New italic text".
<script>
$("#updateValue").click(function() {
$("#inputField").val("New value"); // Set the new value of the input
field
});
</script>
When you click the button, the input field will display "New value".
Example:
<div id="box" style="width: 100px; height: 100px; background-color:
red;"></div>
<button id="changeStyle">Change Style</button>
<script>
$("#changeStyle").click(function() {
$("#box").css("background-color", "blue"); // Change background color to
blue
});
</script>
When you click the button, the background color of the #box element changes to blue.
You can add or remove CSS classes to/from elements to update their styling dynamically.
<script>
$("#toggleClass").click(function() {
$("#box").toggleClass("blueBox"); // Toggle the blueBox class on and off
});
</script>
In this example:
<script>
$("#updateLink").click(function() {
$("#link").attr("href", "https://newexample.com"); // Update href
attribute
});
</script>
When you click the button, the link’s href attribute will change to "https://newexample.com".
Example:
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button id="addItem">Add Item</button>
<script>
$("#addItem").click(function() {
$("#list").append("<li>Item 3</li>"); // Add new item at the end of the
list
});
</script>
When you click the button, a new item will be added to the end of the list.
Example:
<p id="para">This is a paragraph</p>
<button id="removePara">Remove Paragraph</button>
<script>
$("#removePara").click(function() {
$("#para").remove(); // Remove the <p> element from the DOM
});
</script>
When you click the button, the paragraph is removed from the page.
.addClass()
Add a CSS class to an $("#box").addClass("highlighted");
element
.removeClass()
Remove a CSS class from an $("#box").removeClass("highlighted");
element
.attr()
Update the attribute value of $("#link").attr("href", "newLink.html");
an element
.append() Add content to the end of an $("#list").append("<li>New Item</li>");
Method Description Example
element
.prepend()
Add content to the beginning $("#list").prepend("<li>First
of an element Item</li>");
.remove()
Remove an element from the $("#para").remove();
DOM
Adding new content to an element using jQuery is simple and can be done in various ways.
Whether you're adding new HTML, text, elements, or attributes, jQuery provides methods
that make these operations smooth and flexible.
<script>
$("#addText").click(function() {
$("#message").text(function(index, currentText) {
return currentText + " Added text!"; // Append new text to current
content
});
});
</script>
Action: When you click the button, the existing text inside <p> will be updated to "This is the
old text. Added text!".
<script>
$("#addHTML").click(function() {
$("#container").append("<p>New HTML content added!</p>"); // Append new
HTML
});
</script>
Action: When you click the button, a new <p> element with "New HTML content added!"
will be appended inside the #container div.
<script>
$("#addItem").click(function() {
$("#list").append("<li>Item 3</li>"); // Add new list item at the end
});
</script>
Action: When you click the button, a new item "Item 3" is added to the end of the list.
In jQuery, getting and setting attributes of HTML elements is a straightforward task using the
.attr() method. It allows you to retrieve the value of an attribute or set a new value for an
attribute of an element.
<script>
$("#getLink").click(function() {
var link = $("#myLink").attr("href"); // Get the href attribute
alert("The link is: " + link); // Display the href value
});
</script>
Action: When you click the button, an alert will display the current value of the href attribute,
which is "https://example.com".
✅ 2. Setting Attributes
To set or update the value of an attribute, use the .attr() method with two arguments: the
name of the attribute and the new value you want to set.
<script>
$("#setLink").click(function() {
$("#myLink").attr("href", "https://newsite.com"); // Set new href
attribute
});
</script>
Action: When you click the button, the href attribute of the link will change from
"https://oldsite.com" to "https://newsite.com".
In jQuery, you can easily get and set CSS properties using the .css() method. This method
allows you to work with the inline style of an element, and you can either retrieve the value of a
CSS property or apply a new value.
Here’s how you can get and set CSS properties using jQuery:
<script>
$("#getColor").click(function() {
var color = $("#box").css("background-color"); // Get the background
color
alert("The background color is: " + color); // Show the color in an
alert
});
</script>
Action: When you click the button, it will show an alert with the current background color of the
#box element.
<script>
$("#changeColor").click(function() {
$("#box").css("background-color", "red"); // Set the background color to
red
$("#box").css("width", "300px"); // Set the width to 300px
});
</script>
Action: When you click the button, the background-color of the #box will change to red, and
the width will be updated to 300px.
In jQuery, the .each() method is a utility function that allows you to iterate over a collection of
elements and execute a function for each one. It is often used when you want to apply some
operation to each element in a set, whether you're modifying content, handling events, or
changing styles.
Syntax:
javascript
CopyEdit
$(selector).each(function(index, element) {
// Code to execute for each element
});
index: The index of the current element in the collection (starting from 0).
element: The current element in the iteration, which you can use to manipulate it.
<script>
$("#changeText").click(function() {
$("li").each(function(index) {
$(this).text("Item " + (index + 1) + " has been updated.");
});
});
</script>
Action: When you click the "Change Text" button, the text of each list item will be updated to
"Item X has been updated." where X is the index of the item.
In jQuery, events are actions that occur in the browser, such as a user clicking a button, moving
the mouse, or typing in an input field. You can listen for these events and respond with custom
functions. jQuery simplifies working with events by offering cross-browser compatibility and
concise syntax for attaching event handlers.
javascript
CopyEdit
$(selector).event(function() {
// Code to execute when the event occurs
});
1. click
Action: When the button is clicked, an alert will pop up with the message "Button was
clicked!".
2. mouseenter / mouseleave
The mouseenter and mouseleave events are triggered when the mouse enters or leaves an
element.
<script>
$("#box").mouseenter(function() {
$(this).css("background-color", "orange"); // Change color when mouse
enters
});
$("#box").mouseleave(function() {
$(this).css("background-color", "lightblue"); // Change color when mouse
leaves
});
</script>
Action: When you hover over the div, its background color will change to orange, and when the
mouse leaves, it will return to lightblue.
3. keydown / keyup
The keydown and keyup events are triggered when a key is pressed down or released,
respectively.
Action: When a key is pressed while focused on the input field, an alert will pop up with the
message "A key was pressed!".
4. submit
Action: When the form is submitted, an alert will pop up with the message "Form submitted!",
and the default form submission behavior will be prevented.
EVENT OBJECT
In jQuery, the event object is passed to the event handler function whenever an event occurs. It
contains information and methods related to the event, such as the event type, the target element,
mouse position (for mouse events), key pressed (for keyboard events), and much more.
📌 Syntax:
javascript
CopyEdit
$(selector).on("event", function(event){
// use event object here
});
✅ Example:
<button id="myBtn">Click me</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$("#myBtn").on("click", function(event){
console.log("Event type: " + event.type); // e.g., "click"
console.log("Target element: ", event.target); // the button
console.log("Which key/button: " + event.which); // mouse button or key
code
console.log("Event pageX: " + event.pageX); // x-coordinate on the
page
});
</script>
Property Description
event.type The type of the event (e.g., "click", "keydown")
Property Description
event.target The DOM element that triggered the event
event.currentTarget The element to which the event handler is attached
event.pageX The mouse position relative to the document
event.pageY Same as above, for Y-axis
event.which The button or key that was pressed
event.preventDefault() Prevents the default action
event.stopPropagation() Stops the event from bubbling up
EFFECTS
In jQuery, effects refer to built-in methods that help you create visual animations like showing, hiding,
fading, sliding elements, etc., with minimal code.
Basic Effects
Method Description
Example:
$("#btn").click(function(){
$("#box").toggle();
});
🌫 Fade Effects
Method Description
🎢 Slide Effects
Method Description
Example:
$("#btn").click(function(){
$("#box").slideToggle("fast");
});
🛠 Custom Animation
$("#box").animate({
left: '250px',
opacity: '0.5',
height: 'toggle'
}, 1000); // duration in milliseconds
⏱ Speed Options
"slow" (~600ms)
"fast" (~200ms)
Or any number in milliseconds: 1000, 1500, etc.
Basic Syntax:
$(selector).animate({properties}, duration, easing, callback);
<script>
$("#box").click(function() {
$(this).animate({
width: "200px",
height: "200px"
});
</script>
Notes:
Only numeric properties can be animated (e.g., width, height, left, opacity).
Non-numeric properties like background-color require jQuery UI or other plugins.
The duration can be a number in milliseconds or strings like "slow" or "fast".
You can chain .animate() calls for multiple animations.
DOM traversal in jQuery means moving through (or “navigating”) the elements in the HTML document
— up, down, and sideways in the DOM tree. jQuery makes this super easy with a set of traversal
methods.
Example
$(this).parent();
.parents()
Example
.closest()
Example
$(this).closest(".container");
$("#main").children();
.find()
// Get value
let name = $("#name").val();
// Set value
$("#name").val("John Doe");
Checkbox / radio:
// Check if checked
let isChecked = $("#check1").is(":checked");
// Check it
$("#check1").prop("checked", true);
// Uncheck
$("#check1").prop("checked", false);
🔄 3. Form Submission
Basic submit event:
$("#myForm").submit(function(e) {
e.preventDefault(); // prevent actual submission
alert("Form submitted!");
});
Javascript Libraries
JavaScript libraries are pre-written JavaScript code that help you perform common tasks faster and
easier — like DOM manipulation, animations, AJAX calls, form validation, and more. Here’s a list of
popular and widely-used JavaScript libraries, grouped by their purpose:
Still used in many projects for simpler syntax and cross-browser support.
2. UI & Animation
🔹 GSAP (GreenSock Animation Platform)
Anime.js
D3.js
4. Form Validation
🔹 Validator.js
Parsley.js
For example, if you have a form and want to submit it without refreshing the page, you can use
jQuery to capture the form submission event, prevent the default behavior using
e.preventDefault(), collect form data using .val(), and send it to the server using $.ajax().
Once the server responds, you can update the HTML content of a specific element using
.html() or display a message accordingly. This technique is widely used in modern web
development to create a smoother and more interactive user experience.