jQuery AJAX

jQuery simplifies asynchronous HTTP requests with its powerful AJAX methods, enabling developers to load and exchange data with servers dynamically without requiring a page refresh.

1. AJAX Helper Methods

Method Description Syntax Example
load() Loads data from a server and places it into the selected element. $(selector).load(url, [data], [callback]) $("#result").load("example.html #content");
$.get() Sends an HTTP GET request to retrieve data. $.get(url, [data], [callback], [dataType]) $.get("data.json", function(response) { console.log(response); });
$.post() Sends an HTTP POST request to send data to the server. $.post(url, [data], [callback], [dataType]) $.post("submit.php", { name: "John" }, function(data) { alert(data); });
$.getJSON() Sends an HTTP GET request and expects JSON-formatted data as a response. $.getJSON(url, [data], [callback]) $.getJSON("data.json", function(response) { console.log(response); });
$.getScript() Loads and executes a JavaScript file from the server. $.getScript(url, [callback]) $.getScript("script.js", function() { console.log("Script loaded!"); });

2. General $.ajax() Method

The $.ajax() method provides full control over AJAX requests with extensive options.

Syntax

$.ajax({
    url: "url",
    type: "GET/POST",
    dataType: "json/html/xml/text",
    data: { key: "value" },
    success: function(response) {
        // Handle success
    },
    error: function(xhr, status, error) {
        // Handle error
    },
    complete: function(xhr, status) {
        // Always execute after success or error
    }
});

Try It Now

Options

Option Description
url Specifies the URL to send the request to.
type The HTTP request method (GET, POST, PUT, DELETE, etc.). Default is GET.
data Data to be sent to the server (in key-value pairs or JSON format).
dataType Expected data type of the response (e.g., json, html, xml, text).
success Callback function executed when the request succeeds.
error Callback function executed when the request fails.
complete Callback function executed after the request (both success and error).
async Boolean value to enable/disable asynchronous requests (default is true).
beforeSend A function executed before the request is sent.
timeout Sets a timeout in milliseconds for the request.

3. AJAX Events

jQuery provides global AJAX event methods that can be used to monitor AJAX requests.

Event Description Example
ajaxStart Fires when the first AJAX request is started. $(document).ajaxStart(function() { console.log("AJAX started!"); });
ajaxStop Fires when all AJAX requests have completed. $(document).ajaxStop(function() { console.log("All AJAX requests complete!"); });
ajaxSend Fires just before an AJAX request is sent. $(document).ajaxSend(function(event, xhr, options) { console.log("Request sent to: " + options.url); });
ajaxComplete Fires after an AJAX request completes (success or error). $(document).ajaxComplete(function(event, xhr, options) { console.log("Completed: " + options.url); });
ajaxError Fires when an AJAX request fails. $(document).ajaxError(function(event, xhr, options, error) { console.log("Error: " + error); });
ajaxSuccess Fires when an AJAX request succeeds. $(document).ajaxSuccess(function(event, xhr, options) { console.log("Successful: " + options.url); });

4. Examples of Common AJAX Scenarios

Basic GET Request

<!DOCTYPE html>
<html>
<head>
    <title>AJAX GET Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#loadData").click(function() {
                $.get("data.txt", function(response) {
                    $("#result").html(response);
                });
            });
        });
    </script>
</head>
<body>
    <button id="loadData">Load Data</button>
    <div id="result"></div>
</body>
</html>

Try It Now

Basic POST Request

<!DOCTYPE html>
<html>
<head>
    <title>AJAX POST Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#sendData").click(function() {
                $.post("submit.php", { name: "John", age: 25 }, function(response) {
                    $("#result").html(response);
                });
            });
        });
    </script>
</head>
<body>
    <button id="sendData">Send Data</button>
    <div id="result"></div>
</body>
</html>

Try It Now

AJAX with $.ajax()

<!DOCTYPE html>
<html>
<head>
    <title>AJAX with $.ajax()</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#fetchData").click(function() {
                $.ajax({
                    url: "data.json",
                    type: "GET",
                    dataType: "json",
                    success: function(response) {
                        $("#result").html("Name: " + response.name + ", Age: " + response.age);
                    },
                    error: function(xhr, status, error) {
                        console.error("Error: " + error);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="fetchData">Fetch Data</button>
    <div id="result"></div>
</body>
</html>

Try It Now

5. Key Points

  • Use AJAX helper methods (get(), post()) for simple cases.
  • Use $.ajax() for advanced configurations like timeouts, custom headers, and error handling.
  • Utilize global AJAX event handlers to monitor requests across the application.
  • Always validate and sanitize data sent to the server for security purposes.