jQuery
jQuery is a fast, lightweight, and easy-to-use JavaScript library that simplifies tasks like HTML manipulation, animations, and event handling. With just a few lines of code, you can create interactive and dynamic web pages more efficiently.
Introduction to jQuery
- What is jQuery?
- Why uses jQuery?
- Advantages of jQuery over JavaScript
- Downloading & Installing jQuery
- jQuery CDN (Content Delivery Network)
- jQuery Basics vs. Vanilla JavaScript
Getting Started with jQuery
- Writing your first jQuery script
- Selecting elements with jQuery ( $() function)
- Document Ready Event ( $(document).ready() )
- jQuery Syntax & Conventions
- Handling Multiple jQuery Versions
jQuery Selectors
- Basic Selectors ( id , class , element )
- Attribute Selectors ( [attribute=value] )
- Hierarchy Selectors ( parent > child , parent child , prev + next )
- Filtering Selectors ( :first , :last , :even , :odd , :not() )
- Form Selectors ( :input , :text , :checkbox , :radio , :selected )
jQuery Events
- Binding & Unbinding Events ( on() , off() )
- Mouse Events ( click , dblclick , mouseenter , mouseleave )
- Keyboard Events ( keydown , keyup , keypress )
- Form Events ( focus , blur , change , submit )
- Event Object ( event.preventDefault() , event.stopPropagation() )
- Event Delegation ( delegate() , on() for dynamic elements)
jQuery Effects & Animations
- Show/Hide Elements ( show() , hide() , toggle() )
- Fading Effects ( fadeIn() , fadeOut() , fadeToggle() , fadeTo() )
- Sliding Effects ( slideUp() , slideDown() , slideToggle() )
- Custom Animations ( animate() )
- Stopping Animations ( stop() )
- jQuery Queue and Chaining Methods
jQuery DOM Manipulation
- Changing Content ( text() , html() , val() )
- Adding & Removing Elements ( append() , prepend() , after() , before() , remove() , empty() )
- Modifying Attributes ( attr() , prop() , removeAttr() )
- Working with CSS ( css() , addClass() , removeClass() , toggleClass() )
- Working with Dimensions ( width() , height() , innerWidth() , outerWidth() )
jQuery DOM Manipulation
- Changing Content ( text() , html() , val() )
- Adding & Removing Elements ( append() , prepend() , after() , before() , remove() , empty() )
- Modifying Attributes ( attr() , prop() , removeAttr() )
- Working with CSS ( css() , addClass() , removeClass() , toggleClass() )
- Working with Dimensions ( width() , height() , innerWidth() , outerWidth() )
jQuery DOM Manipulation
- Changing Content ( text() , html() , val() )
- Adding & Removing Elements ( append() , prepend() , after() , before() , remove() , empty() )
- Modifying Attributes ( attr() , prop() , removeAttr() )
- Working with CSS ( css() , addClass() , removeClass() , toggleClass() )
- Working with Dimensions ( width() , height() , innerWidth() , outerWidth() )
jQuery DOM Manipulation
- Changing Content ( text() , html() , val() )
- Adding & Removing Elements ( append() , prepend() , after() , before() , remove() , empty() )
- Modifying Attributes ( attr() , prop() , removeAttr() )
- Working with CSS ( css() , addClass() , removeClass() , toggleClass() )
- Working with Dimensions ( width() , height() , innerWidth() , outerWidth() )
Want to join?
Find a team of digital marketers you can rely on. Every day, we build trust through communication, transparency, and results.
Introduction to jQuery
1. What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library that makes it easier to work with HTML elements, handle events, create animations, and use AJAX. It simplifies DOM traversal, event handling, and cross-browser scripting.
2. Why use jQuery?
Easy to use: Simple and short code compared to JavaScript.
Works on all browsers: No need to worry about compatibility.
Fast DOM manipulation: Quickly change HTML elements.
Built-in animations: Includes show, hide, fade, etc.
AJAX support: Load content from a server without refreshing the page.
3. Advantages of jQuery over JavaScript
| Feature | JavaScript (Without jQuery) | jQuery (With jQuery) |
|---|---|---|
| Selecting an element | document.getElementById("box") |
$("#box") |
| Hiding an element | document.getElementById("box").style.display = "none"; |
$("#box").hide(); |
| Handling a click event | document.getElementById("btn").addEventListener("click", ...) |
$("#btn").click(function(){...}); |
| Animating an element | Requires CSS & JS changes | $("#box").fadeOut(); |
| AJAX requests | Uses fetch() or XMLHttpRequest |
$.ajax() or $.getJSON() |
4. Downloading & Installing jQuery
Using CDN (Content Delivery Network):
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>(Faster, as browsers may already have it cached.)
Downloading Locally:
Download from jquery.com.
Save in your project folder (e.g.,
/js/jquery-3.6.0.min.js).Add it to your HTML file:
<script src="js/jquery-3.6.0.min.js"></script>
5. jQuery CDN (Content Delivery Network)
A CDN allows you to include jQuery directly from an online source instead of downloading it. This improves speed since browsers often cache these files. Example:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
6. jQuery Basics vs. Vanilla JavaScript
jQuery:
$("#btn").click(function(){ $("#text").text("Hello!"); });Vanilla JS:
document.getElementById("btn").addEventListener("click", function() { document.getElementById("text").innerHTML = "Hello!"; });
👉 jQuery makes JavaScript shorter, cleaner, and more readable.
Getting Started with jQuery
1. Writing your first jQuery script
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>jQuery Example</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
</head>
<body>
<h1 id=”heading”>Hello, World!</h1>
<button id=”btn”>Click Me</button>
<script>
$(document).ready(function(){
$(“#btn”).click(function(){
$(“#heading”).text(“Hello, jQuery!”);
});
});
</script>
</body>
</html>
🔎 Step by Step Example details
$(document).ready(function(){ ... });Tells jQuery: “Wait until the entire HTML document is fully loaded before running my code.”
Prevents errors if you try to access elements before they exist.
$("#btn")$→ means jQuery is being used.#btn→ is a selector that finds the element withid="btn"(the button).
.click(function(){ ... });Attaches a click event handler to the button.
This means: “When the button is clicked, run the following function.”
Inside the function:
$("#heading").text("Hello, jQuery!");$("#heading")→ selects the<h1>element withid="heading"..text("Hello, jQuery!")→ changes its text content to Hello, jQuery!
✅ In plain words:
Wait until the page loads.
When the button (
#btn) is clicked → change the heading (#heading) text to Hello, jQuery!
2. Selecting elements with jQuery ($() function)
The basic syntax is:
$(selector).action();
Examples of selectors:
$("p")→ Selects all<p>tags.$("#id")→ Selects the element with a specific ID.$(".class")→ Selects all elements with a given class.$("button")→ Selects all<button>elements.$("ul li")→ Selects all<li>inside a<ul>.
3. Document Ready Event ($(document).ready())
This ensures that jQuery code runs only after the webpage is fully loaded.
$(document).ready(function(){
// your code here
});
✅ Without it, scripts may run before elements exist on the page.
4. jQuery Syntax & Conventions
The basic syntax:
$(selector).action();$→ represents jQuery.selector→ chooses the HTML element (like#id,.class, ortag).action()→ defines what happens (e.g.,hide(),show(),css()).
Example:
$("#hideBtn").click(function(){ $("#text").hide(); });
5. Handling Multiple jQuery Versions
If you are using multiple jQuery versions on the same page, use the noConflict() method to avoid conflicts.
Example:
var jq = jQuery.noConflict();
jq(document).ready(function(){
jq("#btn").click(function(){
jq("#heading").text("Using noConflict()");
});
});
✅ This allows you to use different versions of jQuery safely without interfering with each other.
jQuery Selectors
Basic selectors are used to target HTML elements by ID, Class, or Tag name.
| Selector | Description | Example | Explanation |
|---|---|---|---|
$("#id") |
Selects an element by its ID | $("#heading") |
Selects <h1 id="heading"> |
$(".class") |
Selects all elements with the same class | $(".highlight") |
Selects all elements with class="highlight" |
$("tag") |
Selects all elements by tag name | $("p") |
Selects all <p> tags |
$("selector1, selector2") |
Selects multiple different elements | $("h1, p") |
Selects all <h1> and <p> elements |
Example:
$(“#changeColor”).click(function(){
$(“.text”).css(“color”, “blue”);
});
Used to select elements based on HTML attributes and their values.
| Selector | Description | Example |
|---|---|---|
[attribute] |
Selects elements with a given attribute | $("[required]") |
[attribute='value'] |
Selects elements where attribute = value | $("input[type='password']") |
[attribute!='value'] |
Selects elements where attribute ≠ value | $("img[src!='logo.png']") |
[attribute^='value'] |
Selects elements where attribute starts with value | $("a[href^='https://']") |
[attribute$='value'] |
Selects elements where attribute ends with value | $("img[src$='.png']") |
[attribute*='value'] |
Selects elements where attribute contains value | $("button[name*='submit']") |
Example:
$(“a[href^=’https://’]”).css(“color”, “green”);
Used to select elements based on their relationship in the DOM tree.
| Selector | Description | Example |
|---|---|---|
parent > child |
Selects direct child elements | $("div > p") |
parent child |
Selects all descendants (child + nested) | $("div p") |
prev + next |
Selects immediate next sibling | $("h2 + p") |
prev ~ siblings |
Selects all next siblings | $("h2 ~ p") |
Example:
$(“div > p”).css(“color”, “red”);
Used to filter a group of elements based on position or condition.
| Selector | Description | Example |
|---|---|---|
:first |
Selects the first element | $("li:first") |
:last |
Selects the last element | $("li:last") |
:even |
Selects even-indexed elements (0,2,4,...) | $("li:even") |
:odd |
Selects odd-indexed elements (1,3,5,...) | $("li:odd") |
:not(selector) |
Excludes matching elements | $("li:not(:contains('Banana'))") |
Example:
$(“li:odd”).addClass(“highlight”);
Form selectors help manipulate form elements easily.
| Selector | Description | Example |
|---|---|---|
:input |
Selects all form inputs (input, textarea, select, button) | $(":input") |
:text |
Selects text input fields | $(":text") |
:checkbox |
Selects all checkboxes | $(":checkbox") |
:radio |
Selects all radio buttons | $(":radio") |
:selected |
Selects selected dropdown options | $(":selected") |
:disabled |
Selects disabled form fields | $(":disabled") |
Example:
$(“input:checkbox:checked”).val();
jQuery Events
1. Binding & Unbinding Events (on(), off())
.on()→ Attaches an event handler (works for existing & future elements)..off()→ Removes an event handler.
Example:
// Bind event dynamically
$(“#itemList”).on(“click”, “li”, function(){
alert(“You clicked: ” + $(this).text());
});
// Unbind event
$(“#message”).off(“click”, showMessage);
👉 Use .on() for dynamic elements, .click() only for static ones
2. Mouse Events (click, dblclick, mouseenter, mouseleave)
click→ Runs when clicked.dblclick→ Runs when double-clicked.mouseenter→ Runs when mouse enters element.mouseleave→ Runs when mouse leaves element.
Example:
$(“#btn”).click(function(){ alert(“Button Clicked!”); });
$(“#box”).dblclick(function(){ $(this).css(“background”,”red”); });
$(“#box”).mouseenter(function(){ $(this).addClass(“highlight”); });
$(“#box”).mouseleave(function(){ $(this).removeClass(“highlight”); });
👉 Used for hover effects, double-click actions, etc.
3. Keyboard Events (keydown, keyup, keypress)
keydown→ Fires when key is pressed down.keyup→ Fires when key is released.keypress→ Fires when key is held (deprecated).
Example:
$(“#input”).keydown(function(){
$(“#output”).text(“Key is Pressed Down!”);
});
$(“#input”).keyup(function(event){
$(“#output”).text(“Key Released! Last Key: ” + event.key);
});
$(“#input”).keypress(function(){
$(“#output”).text(“Key is being Pressed!”);
});
👉 Use keydown/keyup in modern browsers
4. Form Events (focus, blur, change, submit)
focus→ When input is selected.blur→ When input loses focus.change→ When input value changes.submit→ When form is submitted.
Example:
$(“#myInput”).focus(function(){ $(this).css(“border”,”2px solid blue”); });
$(“#myInput”).blur(function(){ $(this).css(“border”,”1px solid black”); });
$(“#myForm”).submit(function(event){
event.preventDefault(); // stop form submission
$(“#message”).text(“Form Submitted!”);
});
👉 Useful for validation and UX
5. Event Object (event.preventDefault(), event.stopPropagation())
preventDefault()→ Stops default browser action (like opening a link).stopPropagation()→ Stops event bubbling to parent.
Example:
$(“#myLink”).click(function(event){
event.preventDefault();
alert(“Default action prevented!”);
});
$(“#child”).click(function(event){
event.stopPropagation();
alert(“Child Div Clicked!”);
});
👉 Prevents unwanted navigation or parent trigger
6. Event Delegation (delegate(), on() for dynamic elements)
Problem: Direct binding doesn’t work on dynamically added elements.
Solution: Use
.on()(modern) or.delegate()(old).
Example with .on():
$(“#container”).on(“click”, “.dynamicBtn”, function(){
$(this).text(“Clicked!”).css(“background”,”yellow”);
});
Example with .delegate():
$(“#itemList”).delegate(“.listItem”,”click”,function(){
$(this).css(“color”,”red”).text(“Clicked!”);
});
👉 .on() is preferred today
Summary
Use
.on()for attaching events,.off()for removing.Mouse events detect clicks and hovering.
Keyboard events capture typing.
Form events handle input focus, change, and submission.
preventDefault()stops default action,stopPropagation()stops bubbling.Event Delegation makes dynamic elements responsive to events.
jQuery Effects & Animations
1. Show/Hide Elements (show(), hide(), toggle())
show()→ Displays an element.hide()→ Hides an element.toggle()→ Switches between show & hide.
Example:
$(“#showBtn”).click(function(){ $(“#box”).show(); });
$(“#hideBtn”).click(function(){ $(“#box”).hide(); });
$(“#toggleBtn”).click(function(){ $(“#box”).toggle(); });
👉 Can use speed (slow, fast, milliseconds) & callback
2. Fading Effects (fadeIn(), fadeOut(), fadeToggle(), fadeTo())
fadeIn()→ Gradually shows an element.fadeOut()→ Gradually hides an element.fadeToggle()→ Switches between fadeIn & fadeOut.fadeTo(speed, opacity)→ Fades element to given opacity.
Example:
$(“#fadeInBtn”).click(function(){ $(“#box”).fadeIn(); });
$(“#fadeOutBtn”).click(function(){ $(“#box”).fadeOut(); });
$(“#fadeToggleBtn”).click(function(){ $(“#box”).fadeToggle(); });
$(“#fadeToHalf”).click(function(){ $(“#box”).fadeTo(1000, 0.5); }); // 50% opacity
👉 Creates smooth transitions
3. Sliding Effects (slideUp(), slideDown(), slideToggle())
slideUp()→ Collapses element upward.slideDown()→ Expands element downward.slideToggle()→ Switches between up & down.
Example:
$(“#slideUpBtn”).click(function(){ $(“#panel”).slideUp(); });
$(“#slideDownBtn”).click(function(){ $(“#panel”).slideDown(); });
$(“#slideToggleBtn”).click(function(){ $(“#panel”).slideToggle(); });
👉 Often used for menus & accordions
4. Custom Animations (animate())
Used to animate CSS properties.
Syntax
$(selector).animate({property: value}, speed, callback);Example:
$(“#animateBtn”).click(function(){
$(“#box”).animate({
left: ‘250px’,
opacity: ‘0.5’,
height: ‘150px’,
width: ‘150px’
}, 1000);
});
👉 Animates multiple CSS properties togethe
5. Stopping Animations (stop())
stop()→ Stops current animation immediately.
Example:
$(“#stopBtn”).click(function(){
$(“#box”).stop(); // Stops any animation on #box
});
👉 Useful when user interaction should cancel running effects
6. jQuery Queue & Chaining Methods
Queue → Animations run in sequence by default.
Chaining → Run multiple jQuery methods on same element.
Example (Chaining):
$(“#box”).css(“color”,”white”)
.slideUp(1000)
.slideDown(1000);
Example (Queue Control):
$(“#box”).animate({width: “200px”}, 1000)
.animate({height: “200px”}, 1000);
👉 Both animations run one after another automatically
Summary
Visibility →
show(),hide(),toggle()Fade effects →
fadeIn(),fadeOut(),fadeToggle(),fadeTo()Slide effects →
slideUp(),slideDown(),slideToggle()Custom motion →
animate()Interrupt animations →
stop()Efficiency → Queue & Chaining
jQuery DOM Manipulation
1. Changing Content (text(), html(), val())
text()→ Gets/sets plain text content.html()→ Gets/sets HTML content.val()→ Gets/sets values of form fields.
Example:
$(“#btn1”).click(function(){ $(“#demo”).text(“Hello Text!”); });
$(“#btn2”).click(function(){ $(“#demo”).html(“<b>Hello HTML!</b>”); });
$(“#btn3”).click(function(){ alert($(“#inputBox”).val()); });
👉 Use for text replacement, inner HTML, and form input values
2. Adding & Removing Elements
append()→ Adds content inside element (at the end).prepend()→ Adds content inside element (at the beginning).after()→ Inserts content after element.before()→ Inserts content before element.remove()→ Removes element completely.empty()→ Clears content inside element but keeps element.
Example:
$(“#list”).append(“<li>Appended Item</li>”);
$(“#list”).prepend(“<li>Prepended Item</li>”);
$(“#list”).after(“<p>After the list</p>”);
$(“#list”).before(“<p>Before the list</p>”);
$(“#removeBtn”).click(function(){ $(“#list”).remove(); });
$(“#clearBtn”).click(function(){ $(“#list”).empty(); });
👉 Use for dynamically modifying page structure
3. Modifying Attributes (attr(), prop(), removeAttr())
attr()→ Get/set attribute values.prop()→ Get/set properties (likechecked,disabled).removeAttr()→ Removes attribute.
Example:
$(“#link”).attr(“href”, “https://jquery.com”);
$(“#checkbox”).prop(“checked”, true);
$(“#img”).removeAttr(“alt”);
👉 attr() is for HTML attributes, prop() is for element properties
4. Working with CSS (css(), addClass(), removeClass(), toggleClass())
css()→ Get/set inline CSS.addClass()→ Add a class.removeClass()→ Remove a class.toggleClass()→ Add/remove class dynamically.
Example:
$(“#box”).css(“color”,”red”);
$(“#box”).addClass(“highlight”);
$(“#box”).removeClass(“highlight”);
$(“#box”).toggleClass(“highlight”);
👉 Useful for styling and interactive effects
5. Working with Dimensions (width(), height(), innerWidth(), outerWidth())
width()→ Content width only.height()→ Content height only.innerWidth()→ Includes padding.outerWidth()→ Includes padding + border (+ margin iftrue).
Example:
console.log($(“#box”).width()); // content width
console.log($(“#box”).innerWidth()); // width + padding
console.log($(“#box”).outerWidth()); // width + padding + border
👉 Useful for responsive design & layout calculations
Summary Table
| Category | Methods | Usage |
|---|---|---|
| Content | text(), html(), val() |
Get/set text, HTML, or form values |
| Add/Remove Elements | append(), prepend(), after(), before(), remove(), empty() |
Insert/remove elements |
| Attributes | attr(), prop(), removeAttr() |
Manage attributes & properties |
| CSS & Classes | css(), addClass(), removeClass(), toggleClass() |
Styling & class control |
| Dimensions | width(), height(), innerWidth(), outerWidth() |
Measure element sizes |
jQuery Traversing
Parent & Ancestor Methods
These methods allow you to move upward in the DOM tree — from a child element to its parent or ancestors.
| Method | Description | Example |
|---|---|---|
| parent() | Selects the direct parent of the selected element. | $("span").parent() → selects the immediate parent of <span>. |
| parents() | Selects all ancestor elements (parents, grandparents, etc.) of the selected element. | $("span").parents("div") → selects all ancestor <div> elements. |
| closest() | Selects the nearest ancestor (including the element itself) that matches a specific selector. | $("span").closest("div") → selects the closest <div> parent. |
Example:
$(document).ready(function(){
$(“span”).closest(“div”).css(“border”, “2px solid red”);
});
👉 This highlights the nearest <div> that contains the <span>.
Children & Descendant Methods
These methods allow you to move downward in the DOM tree — from a parent to its children or deeper descendants
| Method | Description | Example |
|---|---|---|
| children() | Selects direct child elements of the selected element. | $("div").children("p") → selects only <p> that are direct children of <div>. |
| find() | Selects all descendant elements (children, grandchildren, etc.) of the selected element. | $("div").find("p") → selects all <p> inside <div>, even nested ones. |
Example:
$(document).ready(function(){
$(“div”).find(“p”).css(“color”, “blue”);
});
👉 This changes the color of all <p> elements inside <div> (including nested ones).
Sibling Methods
These methods allow you to move horizontally — between elements on the same level in the DOM.
| Method | Description | Example |
|---|---|---|
| siblings() | Selects all siblings of the selected element. | $("#p1").siblings() → selects all siblings of <p id="p1">. |
| next() | Selects the immediate next sibling of the selected element. | $("#p1").next() → selects the next <p> after <p id="p1">. |
| prev() | Selects the immediate previous sibling of the selected element. | $("#p2").prev() → selects the previous <p> before <p id="p2">. |
Example:
$(document).ready(function(){
$(“h2”).next().css(“color”, “green”);
});
👉 This makes the paragraph right after <h2> appear green.
Filtering Methods
Filtering methods refine your selection to target specific elements among those already selected.
| Method | Description | Example |
|---|---|---|
| filter() | Selects only elements that match a specific condition or selector. | $("li").filter(".fruit") → selects only <li> with class "fruit". |
| first() | Selects the first element from the matched set. | $("li").first() |
| last() | Selects the last element from the matched set. | $("li").last() |
| eq(index) | Selects an element by its index (starting from 0). | $("li").eq(2) → selects the third <li>. |
| not(selector) | Excludes elements that match the given selector. | $("li").not(".active") → selects all <li> except the one with class "active". |
Example:
$(document).ready(function(){
$(“li”).not(“:contains(‘Banana’)”).css(“background”, “yellow”);
});
👉 This highlights all list items except the one containing “Banana”.
Summary Table
| Category | Direction | Common Methods |
|---|---|---|
| Parent & Ancestor | Upward | parent(), parents(), closest() |
| Children & Descendant | Downward | children(), find() |
| Sibling | Sideways | siblings(), next(), prev() |
| Filtering | Refines selection | filter(), first(), last(), eq(), not() |
jQuery AJAX (Asynchronous JavaScript and XML)
Introduction to AJAX with jQuery
AJAX stands for Asynchronous JavaScript and XML.
It allows you to send and receive data from a web server without reloading the page.
What AJAX Does:
Updates parts of a webpage dynamically.
Fetches or sends data to a server (like submitting a form).
Improves performance and user experience.
Example:
$.ajax({
url: “data.txt”,
success: function(result){
$(“#output”).html(result);
}
});
👉 The content from data.txt will be loaded into the element with id output.
⚙️ $.ajax() , $.get() , $.post() Methods
These are the main jQuery AJAX methods used to communicate with servers.
1. $.ajax() — The Core Method
This is the most powerful and flexible AJAX method.
Syntax:
$.ajax({
url: “file.php”, // The URL to send the request to
type: “GET”, // or “POST”
data: { name: “John” },// Data to send
success: function(response){
alert(“Data: ” + response);
},
error: function(){
alert(“Error occurred!”);
}
});
Key Options:
| Option | Description |
|---|---|
url | The server URL |
type | HTTP method (GET or POST) |
data | Data to send to the server |
success() | Function to execute if the request succeeds |
error() | Function to execute if the request fails |
2. $.get() — Simplified GET Request
Used for fetching data from a server.
Syntax:
$.get(“data.txt”, function(result){
$(“#output”).html(result);
});
✅ This loads the content of data.txt and inserts it into the HTML element with id="output".
3. $.post() — Simplified POST Request
Used to send data securely to the server (e.g., from forms).
Syntax:
$.post(“submit.php”, { name: “John”, age: 25 }, function(response){
alert(“Server says: ” + response);
});
Sends the data
{name: "John", age: 25} to submit.php and alerts the server response.
AJAX Error Handling
When requests fail (like 404 or 500 errors), you can handle them gracefully using the error callback in $.ajax().
Syntax:
$.ajax({
url: “invalidfile.php”,
success: function(result){
$(“#output”).html(result);
},
error: function(xhr, status, error){
alert(“Error: ” + status + ” – ” + error);
}
});
Explanation:
xhr→ XMLHttpRequest object (gives status codes).status→ The error type (e.g., “error” or “timeout”).error→ The actual error message.
The simplest way to load external HTML or text into an element.
Syntax:
$("#content").load("info.html");
This replaces the content of #content with data from info.html.
Example:
$(“#btn”).click(function(){
$(“#content”).load(“data.html #section1”);
});
👉 Loads only the #section1 part from data.html into the current element.
When you make repeated AJAX calls, browsers may cache responses.
You can disable caching or enable it for performance based on your needs.
To Disable Caching:
$.ajaxSetup({ cache: false });
👉 Ensures that each AJAX request gets the most updated data.
To Improve Performance:
Cache static data if it doesn’t change often.
Use JSON instead of XML for faster parsing.
Combine multiple requests when possible.
Cross-Origin Requests (CORS)
CORS (Cross-Origin Resource Sharing) allows AJAX requests between different domains.
✅ Normally, browsers block AJAX calls made to other domains for security reasons.
Example Problem:
Your site example.com tries to get data from api.external.com — browser blocks it.
Solution:
The server must enable CORS using headers like:
Access-Control-Allow-Origin: *In jQuery:
$.ajax({
url: “https://api.openweathermap.org/data/2.5/weather?q=Delhi&appid=YOUR_KEY”,
dataType: “json”,
success: function(data){
console.log(data);
},
error: function(){
alert(“CORS issue or request failed!”);
}
});
✅ If the external server allows CORS, this request will succeed.
Summary Table
| Topic | Description | Example |
|---|---|---|
| $.ajax() | Core method for flexible AJAX requests | $.ajax({ url: "file.php", type: "GET" }) |
| $.get() | Simplified GET request | $.get("data.txt") |
| $.post() | Simplified POST request | $.post("submit.php", { name: "Ali" }) |
| $.getJSON() | Fetch JSON data directly | $.getJSON("data.json") |
| load() | Load external HTML into an element | $("#box").load("page.html") |
| error handling | Handle request failures | error: function(xhr){...} |
| CORS | Cross-domain AJAX requests | Needs Access-Control-Allow-Origin header |
jQuery Form Handling & Validation
Introduction to AJAX with jQuery
AJAX stands for Asynchronous JavaScript and XML.
It allows you to send and receive data from a web server without reloading the page.
What AJAX Does:
Updates parts of a webpage dynamically.
Fetches or sends data to a server (like submitting a form).
Improves performance and user experience.
Example:
$.ajax({
url: “data.txt”,
success: function(result){
$(“#output”).html(result);
}
});
👉 The content from data.txt will be loaded into the element with id output.
⚙️ $.ajax() , $.get() , $.post() Methods
These are the main jQuery AJAX methods used to communicate with servers.
1. $.ajax() — The Core Method
This is the most powerful and flexible AJAX method.
Syntax:
$.ajax({
url: “file.php”, // The URL to send the request to
type: “GET”, // or “POST”
data: { name: “John” },// Data to send
success: function(response){
alert(“Data: ” + response);
},
error: function(){
alert(“Error occurred!”);
}
});
Key Options:
| Option | Description |
|---|---|
url | The server URL |
type | HTTP method (GET or POST) |
data | Data to send to the server |
success() | Function to execute if the request succeeds |
error() | Function to execute if the request fails |
2. $.get() — Simplified GET Request
Used for fetching data from a server.
Syntax:
$.get(“data.txt”, function(result){
$(“#output”).html(result);
});
✅ This loads the content of data.txt and inserts it into the HTML element with id="output".
3. $.post() — Simplified POST Request
Used to send data securely to the server (e.g., from forms).
Syntax:
$.post(“submit.php”, { name: “John”, age: 25 }, function(response){
alert(“Server says: ” + response);
});
Sends the data
{name: "John", age: 25} to submit.php and alerts the server response.
AJAX Error Handling
When requests fail (like 404 or 500 errors), you can handle them gracefully using the error callback in $.ajax().
Syntax:
$.ajax({
url: “invalidfile.php”,
success: function(result){
$(“#output”).html(result);
},
error: function(xhr, status, error){
alert(“Error: ” + status + ” – ” + error);
}
});
Explanation:
xhr→ XMLHttpRequest object (gives status codes).status→ The error type (e.g., “error” or “timeout”).error→ The actual error message.
The simplest way to load external HTML or text into an element.
Syntax:
$("#content").load("info.html");
This replaces the content of #content with data from info.html.
Example:
$(“#btn”).click(function(){
$(“#content”).load(“data.html #section1”);
});
👉 Loads only the #section1 part from data.html into the current element.
When you make repeated AJAX calls, browsers may cache responses.
You can disable caching or enable it for performance based on your needs.
To Disable Caching:
$.ajaxSetup({ cache: false });
👉 Ensures that each AJAX request gets the most updated data.
To Improve Performance:
Cache static data if it doesn’t change often.
Use JSON instead of XML for faster parsing.
Combine multiple requests when possible.
Cross-Origin Requests (CORS)
CORS (Cross-Origin Resource Sharing) allows AJAX requests between different domains.
✅ Normally, browsers block AJAX calls made to other domains for security reasons.
Example Problem:
Your site example.com tries to get data from api.external.com — browser blocks it.
Solution:
The server must enable CORS using headers like:
Access-Control-Allow-Origin: *In jQuery:
$.ajax({
url: “https://api.openweathermap.org/data/2.5/weather?q=Delhi&appid=YOUR_KEY”,
dataType: “json”,
success: function(data){
console.log(data);
},
error: function(){
alert(“CORS issue or request failed!”);
}
});
✅ If the external server allows CORS, this request will succeed.
Conditional Statement in JavaScript
Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform another action.
Different types of conditional statements
If statement
If…else statement
If….else if….else statement
Switch
If Statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
Syntax:
If(condition){
Code to be executed if condition is true
}
Example
<script>
var a=4;
if(a>=0) {
document.write(“Positive Number”);
}
</script>
Write a script to check whether the person’s age is eligible for vote or not.
The else statement
Use the else statement to specify a block of code to be executed if the condition is false
Syntax:
If(condition) {
//code to be executed if the condition is true
} else {
//block of code to be executed if the condition is false
}
Example #1:
<script>
var x=4;
if(x>=0) {
document.write(“This is Positive Number”);
} else {
document.write(“This is Negative Number”);
}
</script>
Example #2:
<script>
var x=5;
if(x%2==0){
document.write(x+” Even Number”);
} else {
document.write(x+” Odd Number”);
}
</script>
If…..else if….else statement
The if…else…if statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.
Syntax:
if(condition1){
Lines of code to be executed if condition 1 is true
} else if(condition2) {
Lines of code to be executed if condition 2 is true
} else {
Lines of code to be executed if condition 1 and condition 2 is false
}
Example #1:
<script>
var v=10;
if(v==1) {
document.write(“Monday”);
} else if(v==2) {
document.write(“Tuesday”);
} else if(v==3) {
document.write(“Wednesday”);
} else if(v==4) {
document.write(“Thursday”);
} else if(v==5) {
document.write(“Friday”);
} else if(v==6) {
document.write(“Saturday”);
} else if(v==7) {
document.write(“Sunday”);
} else {
document.write(“Invalid Number”);
}
</script>
Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement, but it is convenient than if…else…if because it can be used with numbers, characters, etc.
Syntax:
switch(expressions) {
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
default:
code to be executed if above values are not matched;
break;
}
Example:
<script>
var v=5;
switch(v) {
case 1: document.write(“Monday”);
break;
case 2: document.write(“Tuesday”);
break;
case 3: document.write(“Wednesday”);
break;
case 4: document.write(“Thursday”);
break;
case 5: document.write(“Friday”);
break;
case 6: document.write(“Saturday”);
break;
case 7: document.write(“Sunday”);
break;
default:
document.write(“Invalid Number”);
break;
}
</script>
Project area to show.
Want to join?
Find a team of digital marketers you can rely on. Every day, we build trust through communication, transparency, and results.