Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 156 ยท Under the Hood

Legacy JavaScript: XMLHttpRequest and jQuery

Read and modernize older JavaScript - XMLHttpRequest, jQuery basics, var-era patterns like IIFEs and self = this, and why JSONP was replaced by CORS.

Most of the JavaScript you'll be paid to work on wasn't written last week. Company dashboards, WordPress themes, admin panels and popular plugins often date from 2010โ€“2018, before fetch, class, modules and async/await were everywhere. If you only know modern JavaScript, that code can look like a foreign dialect: XMLHttpRequest, dollar signs on every line, var self = this, functions wrapped in mysterious parentheses.

This lesson teaches you to read that code confidently and to know its modern equivalent. You'll make real requests with XMLHttpRequest, see how jQuery worked by building a tiny version of it, decode the common pre-2015 patterns, and learn why JSONP โ€” once a standard trick โ€” is now considered unsafe. You don't need to write new code this way; you need to understand it well enough to fix and modernize it.

XMLHttpRequest: Ajax before fetch

XMLHttpRequest (XHR) is the API that made "Ajax" apps like Gmail possible in the mid-2000s: pages that load data in the background without a full reload. Despite the name, it handles any kind of data โ€” JSON, text, binary โ€” not just XML.

An XHR request has four steps: create the object, open() it with a method and URL, attach event handlers, and send() it. The result arrives later, in an event handler.

About the live examples: the editors on this page run in a sandbox with no server to talk to. Instead of a real API, the examples request data: URLs, which contain their response right inside the URL. The request code is exactly what you'd write for a real endpoint like /api/products.

JS An XMLHttpRequest, step by step

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Things to notice when you read XHR code:

  • Results arrive in callbacks (onload, onreadystatechange), not as return values. Very old code checks if (xhr.readyState === 4 && xhr.status === 200) inside onreadystatechange; onload is the cleaner equivalent.
  • HTTP errors aren't errors. A 404 still fires onload; only network failures fire onerror. fetch behaves the same way, which is why you check response.ok (Fetch).
  • Headers are set with xhr.setRequestHeader("Content-Type", "application/json") after open() and before send().
  • xhr.open(method, url, false) makes a synchronous request that freezes the page until it finishes. It's deprecated on the main thread; if you find one, replace it.

From callbacks to promises

Because XHR uses callbacks, code that needs several requests in order ends up nested deeper and deeper โ€” the "pyramid of doom" from Callbacks. The usual modernization is in two steps: first wrap XHR in a Promise, then replace it with fetch and async/await.

JS XHR wrapped in a promise vs fetch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

XHR isn't dead, though. It still has one feature fetch makes awkward: upload progress events. If you see xhr.upload.onprogress in a file uploader, that's usually why XHR was chosen, and it's a fine reason to keep it.

jQuery: the library that shaped the web

jQuery (released in 2006) was, for about a decade, on the majority of all websites. Browsers back then disagreed on almost everything: how to attach events, how to select elements, how to make Ajax requests. jQuery hid those differences behind one short, chainable API. Many of its ideas โ€” CSS-selector queries, simple event handling, easy class toggling โ€” were later built into browsers themselves.

Everything in jQuery starts with the $ function. You pass it a CSS selector, get back a jQuery object wrapping all matching elements, and call methods on the whole set at once. Most methods return the same object, so calls can be chained:

JavaScript
// jQuery (read-only โ€” not loaded on this page)
$(document).ready(function () {             // or the shortcut $(function () { ... })
  $(".tab").on("click", function () {
    $(".tab").removeClass("active");
    $(this).addClass("active");             // `this` is the clicked DOM element
    $("#panel").text("Showing " + $(this).data("name")).fadeIn(200);
  });

  $.getJSON("/api/products", function (products) {
    $.each(products, function (i, product) {
      $("#list").append("<li>" + product.name + "</li>");  // careful: HTML injection!
    });
  });
});

Here's what each piece means today:

jQuery Modern JavaScript
$(document).ready(fn) <script type="module"> or defer (runs after parsing), or DOMContentLoaded
$(".item") document.querySelectorAll(".item") (Selecting Elements)
$("#id") document.querySelector("#id") or getElementById("id")
.on("click", fn) / .off() addEventListener() / removeEventListener() (Events)
.addClass(), .removeClass(), .toggleClass() classList.add(), .remove(), .toggle() (Styles and Classes)
.text() / .html() textContent / innerHTML (Changing Content)
.attr(), .data("name") getAttribute(), dataset.name
.css("color", "red") style.color = "red" or, better, a class
.hide(), .show(), .fadeIn() hidden attribute, classes and CSS transitions
.append(), .remove() append(), remove() (Creating Elements)
.closest(), .parent(), .find() closest(), parentElement, querySelectorAll() (DOM Traversal)
$.ajax(), $.getJSON() fetch()
$.each(), $.map() forEach(), map()
$.extend({}, a, b) { ...a, ...b } or structuredClone()

The key behavioral difference: jQuery methods work on every matched element and silently do nothing if there are none. document.querySelector() returns null when nothing matches, so calling a method on it throws. When converting, decide for each line whether you need one element or a loop.

Build a tiny jQuery to see how it worked

The best way to understand jQuery's $ is to write a miniature one. It's just a function that wraps a list of elements in an object whose methods loop over the list and return this for chaining:

A 25-line mini jQuery

Real jQuery is far bigger โ€” it handles animations, event delegation, Ajax, and quirks of browsers long gone โ€” but the core idea is exactly this. Should you remove jQuery from an old project? Not necessarily all at once. It still works, and version 3.x and later are maintained. But for new code, the built-in DOM APIs do the same jobs without an extra download.

Watch out for HTML strings. Legacy code often builds markup by concatenating strings: $("#list").append("<li>" + product.name + "</li>"). If product.name comes from a user, that's an XSS hole. When you modernize, use textContent or create elements instead (JavaScript Security Basics).

Pre-2015 patterns you'll recognize

Before let, class, arrow functions and modules, developers invented patterns to get the same results. Here's how to read the most common ones.

Legacy pattern What it was for Modern replacement
var x = โ€ฆ the only way to declare variables const / let
(function () { โ€ฆ })(); (IIFE) private scope, avoid globals modules, block scope
var self = this; (or that, _this) keep this inside callbacks arrow functions
function Person(name) { this.name = name; } + Person.prototype.greet = โ€ฆ classes class
arguments and Array.prototype.slice.call(arguments) variable number of arguments rest parameters ...args
`x = x "default";`
"Hello, " + name + "!" building strings template literals
typeof x === "undefined" safe check for missing values still valid, or x === undefined / ??
`window.MyApp = window.MyApp {};`
JS Reading and rewriting old patterns

Press Run (or Ctrl + Enter) to see the console output here.

No output.

One trap from that table deserves repeating: x = x || "default" replaces 0, "" and false too, while a default parameter (or ??) only kicks in for undefined (Best Practices). When you modernize, check that nobody relied on the old behavior.

JSONP: a clever hack you should not use

Before CORS existed, browsers blocked a page from reading responses from other domains with XHR. But <script> tags could load scripts from anywhere. JSONP ("JSON with padding") abused that loophole: instead of plain JSON, the server returned JavaScript that called a function with the data.

HTML
<!-- Read-only: how JSONP worked -->
<script>
  function handleWeather(data) {          // must be a global function
    console.log(data.temperature);
  }
</script>
<script src="https://weather.example.com/today?callback=handleWeather"></script>

<!-- The server responded with executable code, not JSON: -->
<!-- handleWeather({"temperature": 21, "city": "Lisbon"}); -->

jQuery made this almost invisible with $.ajax({ dataType: "jsonp" }), so you may find it in old code without the word "script" anywhere. It's unsafe for several reasons:

  • You run the other server's code with full power. The "data" is really a script. If that server is hacked or turns malicious, it can read your page, steal tokens, or redirect users.
  • Any website can read the data. A JSONP endpoint that returns private data for a signed-in user (using their cookies) can be called from an attacker's page too, which leaks that data.
  • Only GET, and poor error handling. A failed script load gives you almost no information, and there's no clean way to send headers or a body.

The modern replacement is CORS: the other server sends headers such as Access-Control-Allow-Origin that tell the browser which sites may read its responses, and you use a normal fetch() (Cross-Origin Requests and CORS). If a legacy integration still uses JSONP, replacing it is a security fix, not just cleanup.

Modernizing legacy code safely

When you inherit an old codebase, resist the urge to rewrite everything at once:

  1. Understand before changing. Read the code, run it, and note what each part does.
  2. Add tests around the behavior you're about to touch (Testing JavaScript), so you'll know if you break something.
  3. Change in small steps: var โ†’ let/const, then string concatenation โ†’ template literals, then callbacks โ†’ promises, one file at a time.
  4. Let tools help. A linter with no-var and prefer-const rules finds the easy wins; a bundler lets old and new files coexist (Tooling).
  5. Remove jQuery last, usually feature by feature, once nothing depends on it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An XHR request receives a 404 response. Which handler runs?

    onerror only fires for network failures. Any HTTP response, including 404 and 500, fires onload, just as fetch resolves for them.
  2. 2. What is the modern equivalent of jQuery's $(".item").addClass("on")?

    jQuery methods apply to every matched element, so you need querySelectorAll plus a loop, and classList.add adds a class without removing others.
  3. 3. Why did older code write var self = this; before a callback?

    Each regular function call sets its own this. Arrow functions don't, so in modern code they replace the self trick.
  4. 4. What is the main security problem with JSONP?

    JSONP executes code from another server and can't restrict which sites read the response. CORS with fetch replaced it.
  5. 5. Which is still a good reason to use XMLHttpRequest today?

    Upload progress events are XHR's remaining practical advantage. For everything else, fetch is simpler and promise-based.

Summary

  • XMLHttpRequest makes requests with open(), event handlers and send(); onload fires for every HTTP response, so check status.
  • Modernize XHR by wrapping it in a promise, then switch to fetch with async/await. Keep XHR only for upload progress.
  • jQuery's $ wraps a set of elements and chains methods over all of them; every method has a built-in DOM equivalent today.
  • Recognize pre-2015 patterns โ€” var, IIFEs, self = this, constructor functions, arguments, || defaults โ€” and their modern replacements.
  • JSONP runs another server's code and leaks data to any site; replace it with CORS and fetch.
  • Modernize gradually, with tests and a linter guarding each step.

Next: Project: To-Do App โ€” put everything together and build a complete app with modern JavaScript.