Skip to main content

Archive

Show more

jQuery AJAX Load

jQuery - AJAX Load

AJAX Load is a jQuery method used to load data from the server and insert it into the selected HTML element without refreshing the entire page.


1. Basic Syntax

The basic syntax of the load() method is:

$(selector).load(url, data, complete);
  • selector: The HTML element where the loaded content will be inserted.
  • url: The URL of the server-side resource to retrieve data from.
  • data: Optional. Data to be sent to the server along with the request.
  • complete: Optional. A callback function that is executed when the request completes.

The load() method fetches data from the server using an AJAX request and inserts it into the selected HTML element.


2. Loading HTML Content

You can use the load() method to load HTML content from the server and insert it into a specified element.

Here's an example:

// Load HTML content into a div element
$("#content").load("content.html");

This code fetches the content of content.html from the server and inserts it into the <div id="content"> element.


3. Loading Data with Parameters

The load() method allows you to send data to the server along with the request.

Here's an example:

// Load data with parameters
$("#result").load("search.php", { query: "jquery" });

In this example, the load() method sends a GET request to search.php with the parameter query=jquery, and inserts the returned data into the <div id="result"> element.


4. Callback Function

You can use a callback function to perform additional actions after the data has been loaded.

Here's an example:

// Load data and perform actions after completion
$("#content").load("content.html", function(response, status, xhr) {
    if (status === "success") {
        console.log("Content loaded successfully:", response);
    } else {
        console.error("Error loading content:", xhr.statusText);
    }
});

In this example, the callback function logs a message to the console indicating whether the content was loaded successfully or if there was an error.


5. Conclusion

AJAX Load is a convenient method in jQuery for dynamically loading content from the server and updating the DOM without a full page refresh. By using the load() method, developers can create more responsive and interactive web applications.

Comments