How to Use jQuery load() to Inject HTML

This article explains how to fetch remote HTML content and inject it directly into a DOM element using jQuery's .load() method. You will learn the core syntax, how to implement basic requests, how to load specific fragments of an external document, and how to handle server responses using callback functions.

Basic Syntax

The .load() method is the simplest way to execute an AJAX request and insert the returned HTML into the selected element.

$(selector).load(url, data, complete);
  • url (String, required): The URL to which the request is sent.
  • data (PlainObject or String, optional): A set of query string parameters or an object sent to the server. If an object is passed, a POST request is used; otherwise, a GET request is used.
  • complete (Function, optional): A callback function executed when the request finishes.

Basic Example: Loading Entire Files

To fetch content from a file named content.html and inject it into a <div> with the ID #container, use the following code:

<div id="container">Content will load here.</div>
<button id="load-btn">Load Content</button>

<script>
$('#load-btn').on('click', function() {
    $('#container').load('content.html');
});
</script>

When the button is clicked, jQuery performs an asynchronous GET request to content.html, replaces the contents of #container, and parses any scripts included in the injected content.

Loading Page Fragments

The .load() method allows you to load only a specific portion of the target document by appending a CSS selector to the URL string, separated by a space.

$('#container').load('content.html #target-section');

In this example, jQuery fetches content.html, parses the returned document, extracts the element matching #target-section, and injects only that element into #container.

Passing Data to the Server

You can pass parameters to the server by providing a data argument:

// Sends a POST request with the specified parameters
$('#container').load('user-profile.php', { userId: 42, view: 'summary' });

Handling Completion and Errors

To perform actions after the HTML is inserted, or to handle errors gracefully, supply a callback function. The callback receives three arguments: the response text, the status string, and the jqXHR object.

$('#container').load('content.html', function(responseText, statusText, xhr) {
    if (statusText === 'success') {
        console.log('Content loaded successfully.');
    } else if (statusText === 'error') {
        console.error('Error loading content: ' + xhr.status + ' ' + xhr.statusText);
        $('#container').html('<p>Failed to load requested data.</p>');
    }
});