LEARN BUILD GROW TOGETHER
DEVELOPER LEARNING HUB
Learn. Build. Grow Together.

Practical tutorials, real-world examples and interview preparation.

.NETC#SQL SERVERANGULAR
Home /AJAX /jQuery: Complete Developer Learning Guide

jQuery: Complete Developer Learning Guide

jQuery: Complete Developer Learning Guide for Beginners to Advanced

jQuery: Complete Developer Learning Guide

From beginner to advanced — understand selectors, DOM manipulation, events, Ajax, JSON, plugins, security, and practical integration with ASP.NET Core applications.

Introduction

jQuery has been used for years to build interactive web pages and remains part of many business applications. Developers maintaining ASP.NET MVC, ASP.NET Core MVC and Razor Pages projects may encounter jQuery in form validation, event handling, partial views, Ajax requests and third-party plugins.

This guide starts with the browser and JavaScript foundations needed to understand jQuery, then progresses through selectors, DOM manipulation, events, asynchronous requests, security, performance and .NET integration. Each topic uses original explanations and practical examples designed to make the underlying idea clear.

How to use this guide: Read the concepts in order, run the examples in a small HTML page, and then connect the browser code to an ASP.NET Core endpoint. The handwritten notes supplied for this guide informed the topic selection; outdated examples and inaccurate shortcuts have been revised for current development practices.
Version baseline: Examples use the jQuery 4.0.0 API where applicable. jQuery 4.0 is the current stable major release listed by the official project. Existing applications may need an upgrade review before changing versions, especially when older plugins or legacy browser support are involved.

What Is jQuery?

jQuery is a JavaScript library that provides a concise API for selecting and working with DOM elements, handling events, applying effects, and making asynchronous HTTP requests. Its central workflow is often described as select something, then do something with it.

The browser already provides JavaScript and DOM APIs. jQuery wraps many common operations in a consistent, chainable API that can be especially useful in server-rendered applications and established projects.

What jQuery commonly helps with

  • Finding elements using CSS-style selectors.
  • Changing text, attributes, properties, classes and styles.
  • Responding to user actions such as clicks, input and form submission.
  • Adding, removing and traversing DOM elements.
  • Sending asynchronous requests to server endpoints.
  • Integrating plugins such as validation and data grids.
Modern perspective: jQuery is still relevant in many existing applications, including ASP.NET MVC and Razor Pages projects. For new interfaces, also understand native JavaScript and the framework already used by the application. Do not add jQuery when it solves no real problem.

How jQuery Fits into a Web Application

HTML defines the page structure, CSS controls presentation, JavaScript provides browser-side behavior, and jQuery offers helper methods over JavaScript and the DOM. An ASP.NET Core application can render HTML on the server and use jQuery in the browser to respond to interactions and call controller or API endpoints.

Browser
  |
  +-- HTML document --> DOM tree
  |
  +-- CSS -----------> visual presentation
  |
  +-- JavaScript ----> application behavior
          |
          +-- jQuery --> selectors, events, DOM helpers, Ajax
          |
          +-- HTTP request --> ASP.NET Core endpoint
                                  |
                                  +-- business logic
                                  +-- database / services
LayerResponsibility
HTML / RazorRender semantic page markup and form fields.
CSS / BootstrapControl layout, spacing and visual states.
JavaScript / jQueryHandle browser interactions and update the page.
ASP.NET CoreValidate requests, execute application logic and return a response.
DatabasePersist application data.

Setup, Installation and Version Selection

Use the current stable jQuery release for new work unless a required plugin or application dependency imposes a compatibility constraint. The official download page currently lists jQuery 4.0.0 as the latest stable release. jQuery 3.7.1 remains listed as the latest 3.x release, but the 3.x branch receives only critical fixes.

CDN setup

<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script src="/js/site.js"></script>

Place the jQuery script before scripts that use $ or jQuery. If your page uses a Content Security Policy or Subresource Integrity, configure the appropriate attributes and policy for the exact CDN asset you choose.

Local installation with npm

npm install jquery

For a bundler-based project, import jQuery in the entry point or module that needs it. Follow the build tool's conventions rather than adding a second global script reference.

Full build vs slim build

BuildIncludesChoose it when
Full buildCore, Ajax, effects and the usual API surface.Your application uses $.ajax(), animations or related modules.
Slim buildSmaller build without Ajax and effects modules.You only need the supported core functionality and have verified the application does not rely on omitted modules.
Version note: jQuery 4.0 removes support for older browsers including IE 10 and below, and has breaking changes. Check the official upgrade guide before upgrading a legacy application.

Your First jQuery Program and Document Ready

Use $() to create a jQuery collection from a selector, DOM element, or other supported input. A jQuery collection is not the same thing as a single native DOM element.

$(function () {
    $("#welcome").text("Hello from jQuery!");
});

The short form above runs when the DOM is ready for manipulation. The longer equivalent is $(document).ready(function () { ... }).

DOM ready vs window load

EventWhen it runsTypical use
DOM readyWhen the HTML has been parsed and the DOM is ready.Attach handlers, find elements and initialize UI behavior.
Window loadAfter the page and dependent resources such as images have finished loading.Work that specifically requires fully loaded page resources.
$(function () {
    console.log("DOM is ready");
});

$(window).on("load", function () {
    console.log("Page resources have loaded");
});
Modern alternative: Native JavaScript also provides DOMContentLoaded. Do not use the removed jQuery shorthand $(window).load(handler); use $(window).on('load', handler) when needed.

Selectors and Selection Basics

Selectors identify the elements that jQuery should work with. Most jQuery selectors use familiar CSS selector syntax, so knowledge of CSS selectors makes jQuery easier to learn.

SelectorMeaningExample
*All elements$('*')
#idElement with an ID$('#saveButton')
.classElements with a class$('.validation-message')
elementElements by tag name$('input')
ancestor descendantMatching descendants at any depth$('form input')
parent > childDirect children only$('ul > li')
A + BImmediately following sibling$('h2 + p')
A ~ BFollowing sibling elements$('h2 ~ p')
[name='value']Attribute equals a value$('[type="email"]')
[name^='prefix']Attribute begins with a value$('[name^="User"]')
// Select by ID, class, element and attribute.
const $form = $("#employeeForm");
const $rows = $(".employee-row");
const $inputs = $("input");
const $email = $('input[type="email"]');

// Limit a search to a particular area.
const $buttons = $form.find("button");
Best practice: Prefer stable IDs, meaningful classes and semantic attributes. Avoid selectors that depend on fragile page structure or broad selectors that unintentionally match unrelated controls.

jQuery Objects, DOM Elements and this

A jQuery object is a collection-like wrapper around zero or more DOM elements. A native DOM element exposes browser properties and methods directly. Use $(element) to wrap a DOM element in jQuery, and .get(0) or [0] to access the first native element.

const nativeButton = document.querySelector("#save");
const $button = $(nativeButton);

// jQuery method
$button.addClass("is-active");

// Native DOM property
nativeButton.disabled = true;

// Convert a jQuery collection to a native element
const firstInput = $("input").get(0);

Inside a traditional jQuery event callback, this usually refers to the DOM element handling the event. Wrapping it with $(this) gives access to jQuery methods.

$(".remove-row").on("click", function () {
    $(this).closest("tr").remove();
});

Filtering and Traversing the DOM

Selectors find an initial set of elements. Filtering narrows that set, while traversal moves through relationships in the DOM tree such as parents, children and siblings.

MethodPurpose
.filter(selector)Keep elements in the current set that match a condition.
.not(selector)Exclude elements that match a condition.
.is(selector)Check whether at least one element in the set matches.
.find(selector)Find matching descendants of the current set.
.children(selector)Find direct child elements.
.parent() / .parents()Get the direct parent or ancestor elements.
.closest(selector)Find the nearest matching element, starting at the current element.
.next() / .prev()Get adjacent sibling elements.
.siblings()Get sibling elements sharing the same parent.
.eq(index) / .first() / .last()Select an element by position.
const $row = $("#employee-42");

$row.find(".status").text("Active");
$row.children("td").addClass("reviewed");

const $form = $("#employeeForm");
const $message = $form.find(".message");
const $nearestPanel = $message.closest(".panel");
Indexing: jQuery collection indexes are zero-based. Therefore $('.row').eq(1) selects the second matching row.

Reading and Updating Content, Values and Attributes

Choose the method that matches the kind of data being changed. Text, HTML markup, form values, HTML attributes and live DOM properties are related but not interchangeable.

MethodUseExample
.text()Read or set text content; inserted text is treated as text.$('#message').text('Saved')
.html()Read or set HTML markup.$('#panel').html('Ready')
.val()Read or set form-control values.$('#email').val()
.attr()Read or set HTML attributes.$('#link').attr('href', '/home')
.prop()Read or set DOM properties such as checked or disabled.$('#agree').prop('checked', true)
.data()Read or set jQuery data associated with elements.$('#item').data('id', 42)
const name = $("#employeeName").val();
$("#summary").text("Employee: " + name);

// Set a form value.
$("#department").val("Engineering");

// Use a property for the current checked state.
const isApproved = $("#approved").prop("checked");

// Set an attribute.
$("#profileLink").attr("href", "/employees/42");
Security: Do not place untrusted user input into .html(). It can create cross-site scripting (XSS) vulnerabilities. Prefer .text() for plain text, and sanitize/encode content when HTML is genuinely required.

Adding, Replacing and Removing Elements

jQuery provides methods to insert markup relative to existing elements, replace elements, and remove content. Understand whether an operation inserts inside or outside the selected element.

MethodWhat it does
.append(content)Adds content at the end, inside each selected element.
.prepend(content)Adds content at the beginning, inside each selected element.
.before(content)Inserts content immediately before each selected element.
.after(content)Inserts content immediately after each selected element.
.empty()Removes child nodes from the selected element, keeping the element itself.
.remove()Removes the selected element and its associated jQuery data/events.
.detach()Removes the element while preserving jQuery data/events for possible reinsertion.
.replaceWith(content)Replaces the selected element with supplied content.
.wrap(content)Wraps each selected element in the supplied structure.
$("#employeeList").append(
    $("<li>").text("New employee")
);

$("#notice").before("<p class='hint'>Please review</p>");

$("#temporaryPanel").empty();   // Keep the panel, remove its children.
$(".obsolete-row").remove();    // Remove matching rows entirely.

append() vs appendTo()

$("#list").append("<li>One</li>");

// Equivalent insertion direction, with the content first.
$("<li>Two</li>").appendTo("#list");
Prefer creating elements with jQuery or DOM APIs and assigning untrusted values through .text() or .val(), rather than concatenating user input into HTML strings.

CSS Classes, Styles and Dimensions

Use classes for reusable visual states and CSS rules. Direct style changes are useful for small dynamic values, but keeping presentation in stylesheets is usually easier to maintain.

$("#saveButton").addClass("is-loading");
$("#saveButton").removeClass("is-loading");
$("#saveButton").toggleClass("is-active");

if ($("#terms").is(":checked")) {
    $("#continueButton").prop("disabled", false);
}

const width = $("#dashboard").width();
const outerWidth = $("#dashboard").outerWidth();
MethodPurpose
.addClass() / .removeClass()Add or remove one or more CSS classes.
.toggleClass() / .hasClass()Toggle a class or check whether it exists.
.css()Read or set inline CSS properties.
.width() / .height()Read or set content dimensions.
.innerWidth() / .innerHeight()Include padding.
.outerWidth() / .outerHeight()Include padding and borders; optionally margins.

Events and Event Objects

An event handler is a function that runs when an event occurs. Common events include click, change, input, submit, keydown, focus, blur and pointer interactions.

$("#saveButton").on("click", function (event) {
    event.preventDefault();
    console.log("Save clicked");
});

$("#searchBox").on("input", function () {
    console.log($(this).val());
});

$("#department").on("change", function () {
    console.log("Selected:", $(this).val());
});

Useful event object members

Member / methodPurpose
event.targetThe original element where the event started.
event.currentTargetThe element whose handler is currently running.
event.preventDefault()Prevents the browser's default action when cancelable.
event.stopPropagation()Stops the event from bubbling to ancestors.
event.which / keyLegacy and modern keyboard-event information; prefer modern KeyboardEvent properties when appropriate.
Prefer .on(): It is the standard jQuery event-registration method. Older shortcuts such as .click(handler) are less flexible and should not be the default in new code.

Event Delegation and Dynamic Elements

Direct event handlers are attached to elements that exist when the handler is registered. If rows or buttons are added later, those new elements will not automatically receive the direct handler. Event delegation attaches one handler to a stable ancestor and filters events using a selector.

// Delegated handler: works for current and future .remove-row buttons.
$("#employeeTable").on("click", ".remove-row", function () {
    $(this).closest("tr").remove();
});

// A delegated form submit handler.
$(document).on("submit", "#employeeForm", function (event) {
    event.preventDefault();
    // Validate and submit the form.
});

Delegation is especially useful for tables, lists, modal content and partial views loaded through Ajax. Choose the nearest stable parent rather than delegating every event from document without a reason.

Effects, Animations and Queues

jQuery effects can show, hide, fade and slide elements. They can be useful for small interface transitions, but avoid using animation as the only way to communicate important state.

$("#details").slideDown(200);
$("#loadingMessage").fadeOut(150);

$("#panel").animate(
    { opacity: 0.5, left: "20px" },
    250,
    function () {
        console.log("Animation completed");
    }
);

// Stop the current animation and clear queued animations.
$("#panel").stop(true, true);
Use CSS transitions for many visual effects. Respect reduced-motion preferences and avoid long or distracting animations in business applications.

Callbacks, Chaining and Iteration

A callback is a function passed to another function so it can be executed later, often after an event, animation or asynchronous operation. Method chaining works because many jQuery methods return the jQuery collection, allowing another method to be called on the result.

$("#message")
    .text("Saved successfully")
    .addClass("success")
    .show();

// Iterate over matched elements.
$(".employee-name").each(function (index) {
    console.log(index, $(this).text());
});

// Iterate over arrays or objects.
const employees = [
    { id: 1, name: "Asha" },
    { id: 2, name: "Ravi" }
];

$.each(employees, function (index, employee) {
    console.log(employee.id, employee.name);
});
APIWhat it iterates
$(selector).each(callback)Elements in the selected jQuery collection.
$.each(collection, callback)Items in an array-like collection or properties in an object.
$.map(array, callback)Transforms values and returns a new result array; callback return values are collected.
In JavaScript, arrays and objects are JavaScript data structures—not jQuery-specific types. Use native for...of, forEach(), map() or Object.entries() when they make the code clearer.

JavaScript Objects, Arrays and JSON

jQuery code is JavaScript, so developers need to understand the data structures commonly passed between the browser and a server.

// Object: one entity with named properties.
const employee = {
    id: 7,
    name: "Asha",
    active: true
};

// Array: an ordered list of values.
const departments = ["Engineering", "Finance", "HR"];

// Array of objects: a common API response shape.
const employees = [
    { id: 7, name: "Asha" },
    { id: 8, name: "Ravi" }
];

// Convert JavaScript data to JSON text.
const jsonText = JSON.stringify(employees);

// Parse JSON text into JavaScript data.
const parsedEmployees = JSON.parse(jsonText);
ConceptMeaning
ObjectA collection of key-value properties.
ArrayAn ordered, zero-indexed list.
JSONA text data format used to exchange structured data.
JSON.stringify()Serializes a JavaScript value into JSON text.
JSON.parse()Parses valid JSON text into a JavaScript value.
JSON is a data format, not the same thing as a JavaScript object. A server response should be valid JSON and should be treated according to its documented contract.

AJAX and HTTP Fundamentals

AJAX means Asynchronous JavaScript and XML. The name is historical: modern applications commonly exchange JSON rather than XML. AJAX describes making an HTTP request from the browser and updating part of the page without performing a full-page navigation.

Understand the HTTP method, URL, request headers, request body, response status and response format. The server remains responsible for authorization, validation and business rules.

HTTP methodTypical meaningCommon use
GETRetrieve a representation; should not change server state.Load a list or detail record.
POSTSubmit data for processing or create a resource.Create an employee or run an operation.
PUTReplace a resource representation at a known URI.Replace a complete record.
PATCHApply a partial update.Change selected fields.
DELETERequest removal of a resource.Delete a record.
Do not put secrets in URLs. Use HTTPS, authorize every server request, validate all input on the server, and use appropriate anti-forgery protection for cookie-authenticated state-changing requests.

jQuery Ajax: $.ajax()

$.ajax() provides detailed control over the request method, URL, headers, request data, expected response type and completion callbacks. It returns a jqXHR object, which supports jQuery's promise-style methods.

$.ajax({
    url: "/api/employees",
    method: "GET",
    dataType: "json"
})
.done(function (employees) {
    console.log("Employees:", employees);
})
.fail(function (jqXHR, textStatus, errorThrown) {
    console.error("Request failed:", textStatus, errorThrown);
});

Common $.ajax options

OptionPurpose
urlEndpoint address.
method / typeHTTP method; prefer method in modern examples.
dataRequest data sent to the server.
dataTypeExpected response data type, such as json.
contentTypeContent type of the request body.
headersAdditional HTTP headers.
processDataWhether jQuery serializes data into a query string by default.
beforeSendCallback before the request is sent.
timeoutRequest timeout in milliseconds.
success / error / completeLifecycle callbacks; jqXHR .done/.fail/.always is another style.
Set dataType: 'json' when you expect JSON. The response's Content-Type header should also accurately identify the representation.

GET and POST Helpers, Load and Form Data

jQuery includes convenience methods for common requests. They are shorter than $.ajax(), but provide fewer configuration options.

// GET: query string data.
$.get("/api/employees", { department: "IT" })
    .done(function (data) {
        console.log(data);
    });

// POST: send form-style data.
$.post("/api/employees", {
    name: "Asha",
    department: "IT"
});

// Load an HTML fragment into an element.
$("#helpPanel").load("/help/employee-form");

.load() is for loading HTML content into selected elements; it is not the same as a general JSON API call. Do not load untrusted HTML into the page.

Send JSON request body

const employee = {
    name: "Asha",
    department: "IT"
};

$.ajax({
    url: "/api/employees",
    method: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(employee)
});

Passing Arrays and Arrays of Objects to an API

When sending arrays, decide whether the server expects URL-encoded form fields or a JSON request body. For a JSON API, serialize the array and set the request content type to application/json.

const employeeIds = [12, 18, 24];

$.ajax({
    url: "/api/employees/bulk-status",
    method: "POST",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(employeeIds)
});

Send an array of objects

const employees = [
    { id: 12, name: "Asha", department: "IT" },
    { id: 18, name: "Ravi", department: "Finance" }
];

$.ajax({
    url: "/api/employees/import",
    method: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(employees)
})
.done(function (result) {
    console.log("Imported:", result);
});
The C# endpoint must accept a compatible request model, such as List<int> or List<EmployeeImportRequest>. The JSON property names and types must match the API contract.

ASP.NET Core Web API Integration

A .NET endpoint receives the browser request, binds the JSON body to a C# model, validates it and returns a response. The browser should not be trusted to enforce business rules.

C# request model and endpoint

public sealed record CreateEmployeeRequest(
    string Name,
    string Department);

[ApiController]
[Route("api/employees")]
public class EmployeesController : ControllerBase
{
    [HttpPost]
    public IActionResult Create(CreateEmployeeRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.Name))
            return BadRequest("Name is required.");

        // Save through an application service.
        return Created("/api/employees/101",
            new { id = 101, request.Name, request.Department });
    }
}

jQuery request

$.ajax({
    url: "/api/employees",
    method: "POST",
    contentType: "application/json",
    dataType: "json",
    data: JSON.stringify({
        name: $("#name").val(),
        department: $("#department").val()
    })
})
.done(function (employee) {
    $("#result").text("Created employee " + employee.id);
})
.fail(function (xhr) {
    $("#result").text(
        xhr.responseText || "Unable to create employee."
    );
});
Use dependency injection and application services for business logic. Keep controller actions focused on HTTP concerns, and return appropriate status codes and response models.

ASP.NET Core MVC / Razor Forms and Anti-Forgery

In cookie-authenticated MVC applications, state-changing form submissions should use anti-forgery protection. ASP.NET Core can generate a request token in the form and validate it on the server.

Razor form

<form id="employeeForm" asp-controller="Employees"
      asp-action="Create" method="post">
    @Html.AntiForgeryToken()

    <input id="name" name="Name" />
    <button type="submit">Save</button>
</form>

Submit using jQuery

$("#employeeForm").on("submit", function (event) {
    event.preventDefault();

    const $form = $(this);

    $.ajax({
        url: $form.attr("action"),
        method: "POST",
        data: $form.serialize()
    })
    .done(function () {
        $("#result").text("Saved.");
    })
    .fail(function () {
        $("#result").text("Save failed.");
    });
});

When posting JSON instead of form-encoded data, read the anti-forgery token from the generated hidden field and send it in the header configured by your ASP.NET Core application. The exact header name must match the server's anti-forgery configuration.

const token = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
    url: "/api/employees",
    method: "POST",
    contentType: "application/json",
    headers: {
        "RequestVerificationToken": token
    },
    data: JSON.stringify({ name: "Asha" })
});
Do not disable anti-forgery validation to make Ajax requests work. Configure the token flow correctly, and remember that CORS, authentication and authorization are separate concerns.

Client-Side Validation and Unobtrusive Validation

Client-side validation gives users faster feedback, but it is not a security boundary. ASP.NET Core model validation must still run on the server.

In MVC/Razor applications, jQuery Validation and jQuery Unobtrusive Validation can read validation metadata rendered into the HTML and attach client-side rules.

<form id="registerForm">
    <label for="email">Email</label>
    <input id="email" name="Email" type="email"
           required data-val="true"
           data-val-required="Email is required." />

    <span data-valmsg-for="Email"
          data-valmsg-replace="true"></span>

    <button type="submit">Register</button>
</form>

Include compatible versions of jQuery, jQuery Validation and jQuery Unobtrusive Validation in the correct order. In ASP.NET Core, use the validation scripts partial where appropriate. If a form is inserted dynamically, parse its validation metadata after insertion using the supported unobtrusive validation APIs.

// After injecting a new form fragment:
const $newForm = $("#newEmployeeForm");
$newForm.removeData("validator");
$newForm.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($newForm);

Working with FormData and File Uploads

Use the browser's FormData API for multipart form submissions, especially when files are included. Disable jQuery's default query-string processing and let the browser set the multipart boundary.

const form = document.querySelector("#documentForm");
const formData = new FormData(form);

$.ajax({
    url: "/api/documents",
    method: "POST",
    data: formData,
    processData: false,
    contentType: false
})
.done(function (response) {
    console.log("Uploaded:", response);
});
Validate file size, extension, content type and file content on the server. Store uploads safely, generate server-side file names, and never trust a filename or MIME type supplied by the browser.

Error Handling, Status Codes and Loading States

Reliable browser code should handle success, validation errors, authentication failures, server errors, timeouts and network failures. Avoid showing raw stack traces or sensitive server details to end users.

const $button = $("#saveButton");
const $status = $("#status");

$button.prop("disabled", true);
$status.text("Saving...");

$.ajax({
    url: "/api/employees",
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify({ name: $("#name").val() })
})
.done(function (response) {
    $status.text("Saved successfully.");
})
.fail(function (xhr, textStatus) {
    if (xhr.status === 400) {
        $status.text("Please check the submitted information.");
    } else if (xhr.status === 401) {
        $status.text("Please sign in again.");
    } else if (xhr.status === 403) {
        $status.text("You are not allowed to perform this action.");
    } else if (textStatus === "timeout") {
        $status.text("The request timed out. Try again.");
    } else {
        $status.text("Something went wrong. Please try again.");
    }
})
.always(function () {
    $button.prop("disabled", false);
});

Deferreds, jqXHR and Promise Interoperability

jQuery Ajax returns a jqXHR object with methods such as .done(), .fail() and .always(). These methods support structured asynchronous handling. Modern JavaScript also provides native Promises and async/await.

function loadEmployees() {
    return $.ajax({
        url: "/api/employees",
        method: "GET",
        dataType: "json"
    });
}

loadEmployees()
    .done(function (employees) {
        console.log(employees);
    })
    .fail(function (xhr) {
        console.error(xhr.status);
    });

Use async/await with jqXHR

async function showEmployees() {
    try {
        const employees = await $.ajax({
            url: "/api/employees",
            dataType: "json"
        });

        console.log(employees);
    } catch (error) {
        console.error("Could not load employees", error);
    }
}
jQuery 4.0 slim excludes Deferreds and Callbacks; the full build includes the broader API. For new asynchronous workflows, native Promises and async/await are often the clearest choice.

AJAX Concurrency, Debouncing and Cancellation

Rapid user input can trigger many requests. Debouncing waits until the user pauses before starting work. Aborting a previous request can prevent stale responses from replacing newer results.

let searchRequest = null;
let searchTimer = null;

$("#search").on("input", function () {
    const term = $(this).val().trim();

    clearTimeout(searchTimer);

    searchTimer = setTimeout(function () {
        if (searchRequest) {
            searchRequest.abort();
        }

        searchRequest = $.ajax({
            url: "/api/employees/search",
            data: { term: term },
            dataType: "json"
        })
        .done(function (results) {
            renderResults(results);
        });
    }, 300);
});

Also consider race conditions: a slower earlier response may arrive after a newer response. Request cancellation and a request sequence identifier are useful techniques, but the server must still enforce authorization and correctness.

Plugins and jQuery UI

A plugin extends jQuery with reusable behavior. A plugin is typically a JavaScript file that registers functionality on the jQuery object or its prototype. Load jQuery before plugins that depend on it.

<!-- Load dependencies in order -->
<script src="/lib/jquery/jquery.min.js"></script>
<script src="/lib/jquery-ui/jquery-ui.min.js"></script>
<script src="/js/site.js"></script>

jQuery UI provides widgets and interactions such as dialogs, date pickers, tabs, autocomplete and drag-and-drop. It is a separate project with its own versioning and compatibility requirements.

Example dialog

$("#confirmDialog").dialog({
    modal: true,
    autoOpen: false,
    buttons: {
        Confirm: function () {
            $(this).dialog("close");
        },
        Cancel: function () {
            $(this).dialog("close");
        }
    }
});

$("#openDialog").on("click", function () {
    $("#confirmDialog").dialog("open");
});
Before selecting a plugin, check maintenance status, supported jQuery versions, accessibility, security history, license and whether native browser functionality already meets the requirement.

DataTables and Server-Side Grids

DataTables is a separate table enhancement library that integrates with jQuery. It can add sorting, paging, searching and server-side processing to HTML tables.

const table = $("#employeeTable").DataTable({
    processing: true,
    serverSide: true,
    ajax: {
        url: "/api/employees/datatable",
        type: "POST"
    },
    columns: [
        { data: "id" },
        { data: "name" },
        { data: "department" }
    ]
});

For large datasets, server-side processing avoids loading every row into the browser. The server must validate paging, sorting and search parameters and enforce authorization. Never concatenate client-provided column names directly into SQL.

noConflict() and Multiple Libraries

jQuery commonly exposes the global names $ and jQuery. Another library may also use $. The noConflict() method releases the global dollar alias so libraries can coexist.

const jq = jQuery.noConflict();

jq(function () {
    jq("#message").text("Using jQuery through jq");
});

Use noConflict(true) only when you intentionally need to release both global names and understand how the application will access jQuery afterward.

Performance and Maintainable jQuery

Good jQuery code is not just short; it is predictable, efficient and easy to maintain. Cache repeated selections, use event delegation for dynamic content, limit DOM reads and writes, and keep behavior in external JavaScript files.

// Less efficient: repeatedly search the same DOM subtree.
$("#employeeTable tr").each(function () {
    $(this).find(".status").addClass("checked");
});

// Better: cache the selection and work with the result.
const $rows = $("#employeeTable tr");
$rows.find(".status").addClass("checked");

Practical guidelines

  • Use specific selectors and cache frequently reused jQuery objects.
  • Delegate handlers for elements created dynamically.
  • Batch DOM changes rather than repeatedly rebuilding large sections.
  • Use CSS classes for visual states instead of many inline style updates.
  • Debounce expensive search and resize handlers.
  • Remove obsolete event handlers and timers when components are destroyed.
  • Keep API calls in a small service/helper layer instead of scattering URLs across views.
  • Use browser developer tools to inspect network requests, console errors and performance.

Security: XSS, CSRF, CORS and Authorization

jQuery runs in the browser, where users can inspect and modify the page and its JavaScript. Client-side checks improve usability but cannot protect server resources.

  • XSS: Treat user-provided content as untrusted. Prefer .text() for plain text and sanitize HTML when HTML is required.
  • CSRF: For cookie-authenticated state-changing requests, use server-validated anti-forgery tokens.
  • CORS: Configure allowed origins, methods and headers on the server. CORS is not authentication.
  • Authorization: Check permissions on every protected server endpoint.
  • Secrets: Never embed API secrets, connection strings or private credentials in browser code.
  • Transport: Use HTTPS and validate server input.
A hidden button, disabled field or JavaScript role check is not access control. A user can call an endpoint directly. Enforce access rules in ASP.NET Core and the underlying service.

Debugging and Testing jQuery Code

Use browser developer tools to debug behavior rather than relying only on alert boxes. Inspect the DOM, event listeners, console, network requests and response payloads.

  • Set breakpoints in the Sources/Debugger panel.
  • Inspect the Network panel for request URL, method, payload, status and response.
  • Use console output temporarily, then remove noisy diagnostics.
  • Test keyboard interaction and accessibility, not only mouse clicks.
  • Test empty, invalid, boundary and unexpected server responses.
  • Use unit or integration tests for server behavior; use browser tests for user workflows.
console.log("Selected rows:", $("#employeeTable tbody tr").length);

debugger; // Pause here while DevTools is open.

Modern JavaScript Alongside jQuery

jQuery does not replace JavaScript. Modern JavaScript provides native APIs for selecting elements, handling events, manipulating classes, making HTTP requests and working with asynchronous operations.

TaskjQueryNative JavaScript
Select element$('#status')document.querySelector('#status')
Set text$('#status').text('Done')document.querySelector('#status').textContent = 'Done'
Add class$('#panel').addClass('active')document.querySelector('#panel').classList.add('active')
Event$('#save').on('click', handler)document.querySelector('#save').addEventListener('click', handler)
HTTP request$.ajax({...})fetch('/api/items')
async function loadItems() {
    const response = await fetch("/api/items");

    if (!response.ok) {
        throw new Error("Request failed: " + response.status);
    }

    return await response.json();
}
Learn both approaches. In a mature jQuery application, use the conventions already established by the project. In a new framework-based application, avoid mixing DOM-manipulation approaches without a clear reason.

Building a Small ASP.NET Core Employee Screen

This example brings together the core ideas: delegated events, safe text rendering, Ajax, loading states and a .NET endpoint. It assumes the page already contains a table body with ID employeeRows and a search input with ID search.

function renderEmployees(employees) {
    const $body = $("#employeeRows").empty();

    employees.forEach(function (employee) {
        const $row = $("<tr>");

        $("<td>").text(employee.id).appendTo($row);
        $("<td>").text(employee.name).appendTo($row);
        $("<td>").text(employee.department).appendTo($row);

        const $removeButton = $("<button>", {
            type: "button",
            class: "remove-employee",
            text: "Remove"
        }).attr("data-id", employee.id);

        $("<td>").append($removeButton).appendTo($row);
        $body.append($row);
    });
}

function loadEmployees() {
    $("#loading").text("Loading...");

    return $.ajax({
        url: "/api/employees",
        method: "GET",
        dataType: "json"
    })
    .done(renderEmployees)
    .fail(function () {
        $("#loading").text("Unable to load employees.");
    })
    .always(function () {
        $("#loading").empty();
    });
}

$("#employeeRows").on("click", ".remove-employee", function () {
    const id = $(this).attr("data-id");

    $.ajax({
        url: "/api/employees/" + encodeURIComponent(id),
        method: "DELETE"
    }).done(function () {
        loadEmployees();
    });
});

$(function () {
    loadEmployees();
});
For a production implementation, add confirmation where appropriate, anti-forgery handling if cookie authentication requires it, clear error messages, authorization on the API, and a response model with stable property names.

Common Interview Questions and Answers

1. What is jQuery?

A JavaScript library that simplifies common DOM selection, manipulation, event handling, effects and Ajax tasks.

2. What is the DOM?

The Document Object Model is the browser's object representation of an HTML document. Scripts can inspect and update its nodes and properties.

3. What is the difference between DOM ready and window load?

DOM ready fires when the document structure is ready for script interaction. Window load waits for dependent page resources to finish loading.

4. What is the difference between .text(), .html() and .val()?

.text() works with text content, .html() works with markup, and .val() works with form-control values.

5. What is the difference between .attr() and .prop()?

Attributes represent markup attributes; properties represent the current state on the DOM object. For example, use .prop('checked') to read the current checkbox state.

6. What is the difference between .empty() and .remove()?

.empty() removes child nodes but keeps the selected element. .remove() removes the selected element itself.

7. What is the difference between .append() and .after()?

.append() inserts content inside the selected element at the end. .after() inserts content as a sibling immediately after it.

8. What is event delegation?

Registering an event handler on a stable ancestor and using a selector to handle matching descendant events, including elements added later.

9. What is AJAX?

A browser technique for exchanging data with a server asynchronously and updating the page without a full navigation.

10. What is JSON?

A text format for structured data exchange. JavaScript provides JSON.parse() and JSON.stringify() to convert between JSON text and JavaScript values.

11. What is the difference between $.each() and .each()?

$.each() iterates over arrays or object properties. .each() iterates over elements in a jQuery collection.

12. What is method chaining?

Calling multiple methods in sequence when a method returns an object that supports the next call.

13. What is noConflict()?

It releases the global $ alias, or selected global aliases, so jQuery can coexist with other libraries.

14. How do you send an array to ASP.NET Core?

For a JSON API, serialize the array using JSON.stringify(), set the request content type to JSON, and bind it to a compatible C# request model.

15. Is client-side validation enough?

No. Server-side validation and authorization are mandatory because browser code can be modified or bypassed.

Practice Exercises and Mini Projects

Beginner exercises

  1. Select all paragraph elements and change their text.
  2. Hide and show a panel using two buttons.
  3. Read a textbox value and display it in a summary element.
  4. Add and remove a CSS class when a checkbox changes.
  5. Append a new list item using a button.

Intermediate exercises

  1. Build a dynamic table and remove rows using delegated events.
  2. Filter a list as the user types, using a debounce.
  3. Load a partial HTML fragment into a panel.
  4. Submit a form with Ajax and show field-level validation errors.
  5. Send an array of selected IDs to an ASP.NET Core endpoint.

Advanced mini project: Employee Directory

  • ASP.NET Core Web API with list, detail, create, update and delete endpoints.
  • jQuery page with search, paging and dynamic table rows.
  • Client-side validation plus server-side model validation.
  • Anti-forgery handling for cookie-authenticated MVC form posts.
  • Loading, empty, success and error states.
  • Authorization checks and safe rendering of server-returned text.

Learning Checklist and Development Best Practices

  • Understand HTML, CSS, JavaScript variables, functions, arrays and objects.
  • Understand the DOM and the difference between native elements and jQuery objects.
  • Use selectors, filters and traversal methods confidently.
  • Read and update text, HTML, form values, attributes and properties correctly.
  • Handle events and use delegation for dynamic content.
  • Use effects carefully and understand callbacks and chaining.
  • Make Ajax requests and handle errors and loading states.
  • Send JSON arrays and objects to ASP.NET Core endpoints.
  • Understand anti-forgery tokens, XSS, CORS and server-side authorization.
  • Use plugins only after checking compatibility and maintenance.
  • Debug requests and test real user workflows.
  • Know when native JavaScript is a better fit than jQuery.

Official Documentation and Learning Resources

What’s Next?

After completing this guide, practice the same UI tasks using modern browser APIs such as querySelector, addEventListener, fetch and classList. This will help you maintain older jQuery applications confidently while making informed choices in newer ASP.NET Core projects.

Next, apply these concepts in a small ASP.NET Core application: render a Razor page, load records from a Web API, validate a form, submit data securely, and handle errors without refreshing the entire page.

Skills Tutorials

Learn • Build • Grow Together