How to use jQuery to make an AJAX request and handle the response



Image not found!!

In jQuery, the $.ajax() function is a versatile tool for executing AJAX (Asynchronous JavaScript and XML) requests and managing their responses. This function serves as a gateway to asynchronous communication, allowing web applications to interact with servers in the background without hindering the user interface. Its simplicity and flexibility make it a cornerstone for developers working with dynamic content and real-time updates.


Here is an example of an AJAX request and handle the response

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>AJAX request and handle the response</title>
</head>

<body>

    <div class="container">
        <div class="row">
            <div class="col-lg-12 text-center mt-5">
                <button id="loadData" class="btn btn-success mb-4" style="font-size: 50px;">Load Data</button>
                <div id="result"></div>
            </div>
        </div>
    </div>


    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>
    <script>
        $(document).ready(function () {
            // Attach a click event to the button
            $("#loadData").click(function () {

                // Make an AJAX request using $.ajax()
                $.ajax({
                    url: 'https://jsonplaceholder.typicode.com/posts/1', // URL to fetch data from
                    type: 'GET', // HTTP method (GET in this case)
                    dataType: 'json', // Expected data type
                    success: function (data) {
                        // Handle the successful response here
                        console.log(data);

                        // Update the content of the result div
                        $("#result").html("User ID: " + data.userId + "<br>Title: " + data.title + "<br>Body: " + data.body);
                    },
                    error: function (xhr, status, error) {
                        // Handle errors here
                        console.error("Error: " + status + ", " + error);
                    }
                });
            });
        });
    </script>
</body>

</html>