jQuery AJAX Introduction

AJAX (Asynchronous JavaScript and XML) allows web pages to update asynchronously by exchanging data with a server without requiring a full page reload. jQuery simplifies AJAX requests with methods that make it easy to fetch or send data to a server.

Why Use jQuery AJAX?

  1. Simplifies the process of making HTTP requests.
  2. Provides shorthand methods like .load(), .get(), .post(), etc.
  3. Compatible with older browsers while offering modern capabilities.
  4. Makes asynchronous programming straightforward.

Common AJAX Methods in jQuery

Method Description
.load() Loads data from a server and places the returned content into the selected element.
$.get() Sends a GET request to the server and retrieves data.
$.post() Sends a POST request to the server.
$.ajax() The most powerful and flexible method for performing custom AJAX requests.

Key jQuery AJAX Methods

  1. $.ajax()
    The most powerful and flexible method for making AJAX requests. It allows you to customize every aspect of the request.

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    $.ajax({
    url: 'server-endpoint.php', // URL of the server-side script
    type: 'GET', // HTTP method (GET, POST, etc.)
    data: { key: 'value' }, // Data to send to the server
    success: function(response) {
    console.log(response); // Handle the server response
    },
    error: function(error) {
    console.error(error); // Handle errors
    }
    });
    $.ajax({ url: 'server-endpoint.php', // URL of the server-side script type: 'GET', // HTTP method (GET, POST, etc.) data: { key: 'value' }, // Data to send to the server success: function(response) { console.log(response); // Handle the server response }, error: function(error) { console.error(error); // Handle errors } });
    $.ajax({
        url: 'server-endpoint.php', // URL of the server-side script
        type: 'GET',               // HTTP method (GET, POST, etc.)
        data: { key: 'value' },    // Data to send to the server
        success: function(response) {
            console.log(response); // Handle the server response
        },
        error: function(error) {
            console.error(error);  // Handle errors
        }
    });
    

    Try It Now

     

  2. $.get()
    A shorthand method for making GET requests.

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    $.get('server-endpoint.php', { key: 'value' }, function(response) {
    console.log(response); // Handle the response
    });
    $.get('server-endpoint.php', { key: 'value' }, function(response) { console.log(response); // Handle the response });
    $.get('server-endpoint.php', { key: 'value' }, function(response) {
        console.log(response); // Handle the response
    });
    

    Try It Now

  3. $.post()
    A shorthand method for making POST requests.

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    $.post('server-endpoint.php', { key: 'value' }, function(response) {
    console.log(response); // Handle the response
    });
    $.post('server-endpoint.php', { key: 'value' }, function(response) { console.log(response); // Handle the response });
    $.post('server-endpoint.php', { key: 'value' }, function(response) {
        console.log(response); // Handle the response
    });
    

    Try It Now

     

  4. $.getJSON()
    A shorthand method for making GET requests and automatically parsing the response as JSON.

    Plain text
    Copy to clipboard
    Open code in new window
    EnlighterJS 3 Syntax Highlighter
    $.getJSON('server-endpoint.php', { key: 'value' }, function(data) {
    console.log(data); // JSON data from the server
    });
    $.getJSON('server-endpoint.php', { key: 'value' }, function(data) { console.log(data); // JSON data from the server });
    $.getJSON('server-endpoint.php', { key: 'value' }, function(data) {
        console.log(data); // JSON data from the server
    });
    

    Try It Now

     

Basic Example: Fetching Data

Example 1: .load()

Fetches and loads content into an element.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<title>jQuery .load() Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function() {
$("#loadButton").click(function() {
$("#content").load("example-content.html");
});
});
</script>
</head>
<body>
<button id="loadButton">Load Content</button>
<div id="content" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>jQuery .load() Example</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { $("#loadButton").click(function() { $("#content").load("example-content.html"); }); }); </script> </head> <body> <button id="loadButton">Load Content</button> <div id="content" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div> </body> </html>
<!DOCTYPE html>
<html>
<head>
    <title>jQuery .load() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#loadButton").click(function() {
                $("#content").load("example-content.html");
            });
        });
    </script>
</head>
<body>
    <button id="loadButton">Load Content</button>
    <div id="content" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div>
</body>
</html>

Try It Now

Example 2: $.get()

Fetches data using a GET request.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<title>jQuery $.get() Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function() {
$("#getData").click(function() {
$.get("example-data.json", function(data) {
$("#result").html("<pre>" + JSON.stringify(data, null, 2) + "</pre>");
});
});
});
</script>
</head>
<body>
<button id="getData">Fetch Data</button>
<div id="result" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>jQuery $.get() Example</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { $("#getData").click(function() { $.get("example-data.json", function(data) { $("#result").html("<pre>" + JSON.stringify(data, null, 2) + "</pre>"); }); }); }); </script> </head> <body> <button id="getData">Fetch Data</button> <div id="result" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div> </body> </html>
<!DOCTYPE html>
<html>
<head>
    <title>jQuery $.get() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#getData").click(function() {
                $.get("example-data.json", function(data) {
                    $("#result").html("<pre>" + JSON.stringify(data, null, 2) + "</pre>");
                });
            });
        });
    </script>
</head>
<body>
    <button id="getData">Fetch Data</button>
    <div id="result" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div>
</body>
</html>

Try It Now

Note: example-data.json should return a JSON response, e.g.:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
{ "name": "John Doe", "age": 30, "city": "New York" }
{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}

Example 3: $.post()

Sends data to the server using a POST request.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<title>jQuery $.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: 30 }, function(response) {
$("#response").html(response);
});
});
});
</script>
</head>
<body>
<button id="sendData">Send Data</button>
<div id="response" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>jQuery $.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: 30 }, function(response) { $("#response").html(response); }); }); }); </script> </head> <body> <button id="sendData">Send Data</button> <div id="response" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div> </body> </html>
<!DOCTYPE html>
<html>
<head>
    <title>jQuery $.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: 30 }, function(response) {
                    $("#response").html(response);
                });
            });
        });
    </script>
</head>
<body>
    <button id="sendData">Send Data</button>
    <div id="response" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div>
</body>
</html>

Try It Now

Note: The submit.php file should process the POST request and return a response.

Example 4: $.ajax()

A more customizable AJAX request.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<title>jQuery $.ajax() Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function() {
$("#customRequest").click(function() {
$.ajax({
url: "example-data.json",
method: "GET",
dataType: "json",
success: function(data) {
$("#output").html("<pre>" + JSON.stringify(data, null, 2) + "</pre>");
},
error: function(xhr, status, error) {
$("#output").html("<p style='color: red;'>Error: " + error + "</p>");
}
});
});
});
</script>
</head>
<body>
<button id="customRequest">Custom AJAX Request</button>
<div id="output" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>jQuery $.ajax() Example</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function() { $("#customRequest").click(function() { $.ajax({ url: "example-data.json", method: "GET", dataType: "json", success: function(data) { $("#output").html("<pre>" + JSON.stringify(data, null, 2) + "</pre>"); }, error: function(xhr, status, error) { $("#output").html("<p style='color: red;'>Error: " + error + "</p>"); } }); }); }); </script> </head> <body> <button id="customRequest">Custom AJAX Request</button> <div id="output" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div> </body> </html>
<!DOCTYPE html>
<html>
<head>
    <title>jQuery $.ajax() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#customRequest").click(function() {
                $.ajax({
                    url: "example-data.json",
                    method: "GET",
                    dataType: "json",
                    success: function(data) {
                        $("#output").html("<pre>" + JSON.stringify(data, null, 2) + "</pre>");
                    },
                    error: function(xhr, status, error) {
                        $("#output").html("<p style='color: red;'>Error: " + error + "</p>");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="customRequest">Custom AJAX Request</button>
    <div id="output" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd;"></div>
</body>
</html>

Try It Now

Summary of Usage

  • Use .load() for simple loading of HTML fragments.
  • Use $.get() or $.post() for basic GET or POST requests.
  • Use $.ajax() when you need more control (e.g., headers, data type, error handling).

Benefits of jQuery AJAX

  • Simplifies handling complex server interactions.
  • Reduces page reloads and improves user experience.
  • Abstracts browser differences for better compatibility.