Paramclasses Academy - Blog

Tutorials Details

←
Post 9 of 15
→

What Is jQuery AJAX?

What Is jQuery AJAX?

October 14, 2026

What Is jQuery AJAX? How to Load Data Without Refreshing the Page


Introduction to jQuery AJAX

AJAX stands for Asynchronous JavaScript and XML. It is a technique used to exchange data between a browser and a server without reloading the entire webpage.

Although AJAX originally included XML in its name, modern web applications commonly exchange JSON data.

jQuery simplifies AJAX operations by providing methods such as:

  • $.ajax()

  • $.get()

  • $.post()

  • $.getJSON()

  • .load()

For example, imagine you are building a student management system. When a user clicks the Load Students button, you can fetch student information from a server and display it on the page without refreshing the browser.

This makes websites more interactive and improves the user experience.

1. What Is AJAX in jQuery?

jQuery AJAX is a collection of methods that helps developers send HTTP requests and process server responses using jQuery.

Without AJAX, a webpage may need to reload to display updated information. With AJAX, JavaScript can request the required data and update only the relevant section of the page.

Traditional page reload vs AJAX

Traditional approach AJAX approach
Often reloads the whole page Can update only a section
May interrupt the current interaction Usually keeps the current page visible
Server response may return an entire page Server can return JSON, HTML or other data
Suitable for regular navigation and form submissions Useful for dynamic updates and background requests

AJAX does not automatically make every request faster. Its main benefit is allowing data exchange without requiring a full-page reload.

2. How Does jQuery AJAX Work?

The basic AJAX process follows these steps:

  1. The user performs an action, such as clicking a button.

  2. jQuery sends an HTTP request to the server.

  3. The server processes the request.

  4. The server returns a response.

  5. JavaScript processes the response.

  6. jQuery updates the relevant content on the webpage.

AJAX request flow

User clicks a button
        |
        v
jQuery sends HTTP request
        |
        v
Server processes request
        |
        v
Server returns data
        |
        v
jQuery displays the response

For example, a shopping website can retrieve product details without reloading the entire product page.

3. How to Include jQuery in an HTML Page

Before using jQuery AJAX, include the jQuery library.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery AJAX Tutorial</title>
</head>
<body>

    <h1>Learn jQuery AJAX</h1>

    <button id="loadBtn">Load Data</button>

    <div id="result"></div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $(document).ready(function () {
            $("#loadBtn").on("click", function () {
                $("#result").text("Button clicked!");
            });
        });
    </script>

</body>
</html>

This example confirms that jQuery is loaded and the button click handler works. The next sections show how to retrieve actual server data.

4. What Is the jQuery $.ajax() Method?

The $.ajax() method is the general-purpose AJAX method in jQuery. It lets you configure the request URL, HTTP method, expected response format, data and callbacks.

Syntax

$.ajax({
    url: "server-url",
    method: "GET",
    dataType: "json",

    success: function (response) {
        // Handle a successful response
    },

    error: function (xhr, status, error) {
        // Handle a failed request
    }
});

Important options

Option Purpose
url Specifies the request destination
method Specifies the HTTP method, such as GET or POST
data Sends data with the request
dataType Specifies the expected response format
success Runs when the request succeeds
error Runs when the request fails
complete Runs after the request finishes, whether successful or not

Example using $.ajax()

This example uses a public demo API to retrieve a post. It requires an internet connection.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery AJAX Example</title>
</head>
<body>

    <button id="loadPost">Load Post</button>

    <div id="postResult"></div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <script>
        $(document).ready(function () {

            $("#loadPost").on("click", function () {

                $("#postResult").text("Loading...");

                $.ajax({
                    url: "https://jsonplaceholder.typicode.com/posts/1",
                    method: "GET",
                    dataType: "json",

                    success: function (response) {
                        $("#postResult").empty();

                        $("<h2>")
                            .text(response.title)
                            .appendTo("#postResult");

                        $("<p>")
                            .text(response.body)
                            .appendTo("#postResult");
                    },

                    error: function () {
                        $("#postResult").text(
                            "Unable to load the post. Please try again."
                        );
                    }
                });

            });

        });
    </script>

</body>
</html>

Expected result: Clicking Load Post retrieves a sample post and displays its title and body.

The example creates HTML elements and uses .text() to display the returned data safely as plain text.

5. What Is the jQuery $.get() Method?

The $.get() method sends an HTTP GET request. It is commonly used to retrieve information from a server.

Syntax

$.get(url, function (response) {
    // Process the response
});

Example

<button id="getBtn">Get User Data</button>
<div id="userResult"></div>

<script>
$("#getBtn").on("click", function () {

    $.get(
        "https://jsonplaceholder.typicode.com/users/1",
        function (response) {

            $("#userResult").empty();

            $("<h3>")
                .text(response.name)
                .appendTo("#userResult");

            $("<p>")
                .text(response.email)
                .appendTo("#userResult");
        }
    ).fail(function () {
        $("#userResult").text("Unable to retrieve user data.");
    });

});
</script>

Expected result: The page displays the sample user's name and email address.

When should you use $.get()?

Use $.get() when you need to retrieve data, such as:

  • Student records

  • Product details

  • Blog posts

  • Search results

  • Public API information

GET requests should not be used to perform actions that change important server-side data.

6. What Is the jQuery $.post() Method?

The $.post() method sends an HTTP POST request. It is useful when submitting data to a server for processing or storage.

Syntax

$.post(url, data, function (response) {
    // Process the response
});

Example

The following example sends sample data to a demo API. It does not save the data permanently.

<button id="postBtn">Submit Sample Data</button>
<div id="postResult"></div>

<script>
$("#postBtn").on("click", function () {

    $.post(
        "https://jsonplaceholder.typicode.com/posts",
        {
            title: "My First AJAX Post",
            body: "Learning jQuery AJAX",
            userId: 1
        },
        function (response) {

            $("#postResult").text(
                "Demo request completed. Returned ID: " + response.id
            );

        },
        "json"
    ).fail(function () {
        $("#postResult").text("Unable to submit the request.");
    });

});
</script>

Important: JSONPlaceholder is a testing API. It simulates creating a resource but does not permanently store the submitted post.

When should you use $.post()?

Common uses include:

  • Submitting a contact form

  • Creating a new record

  • Sending comments

  • Submitting registration details

  • Saving a new task

For real applications, the server must validate the data, check authorization and apply the appropriate security protections.

7. What Is the jQuery $.getJSON() Method?

The $.getJSON() method sends a GET request and expects a JSON response.

JSON stands for JavaScript Object Notation. It is a widely used format for exchanging structured data between applications.

Syntax

$.getJSON(url, function (data) {
    // Process JSON data
});

Example

<button id="jsonBtn">Load JSON Data</button>
<div id="jsonResult"></div>

<script>
$("#jsonBtn").on("click", function () {

    $.getJSON(
        "https://jsonplaceholder.typicode.com/users/1",
        function (user) {

            $("#jsonResult").empty();

            $("<p>")
                .text("Name: " + user.name)
                .appendTo("#jsonResult");

            $("<p>")
                .text("Email: " + user.email)
                .appendTo("#jsonResult");

            $("<p>")
                .text("City: " + user.address.city)
                .appendTo("#jsonResult");

        }
    ).fail(function () {
        $("#jsonResult").text("Unable to load JSON data.");
    });

});
</script>

Expected result: The user's name, email and city are displayed on the webpage.

When should you use $.getJSON()?

Use it when retrieving structured JSON data from an API, such as user profiles, weather information, product lists or application records.

8. What Is the jQuery .load() Method?

The .load() method retrieves data from a URL and inserts the returned content into the selected HTML element.

It is particularly useful when the server returns an HTML fragment.

Syntax

$(selector).load(url);

Example

Suppose a server endpoint named message.html returns:

<h2>Welcome to Our Website</h2>
<p>This content came from the server.</p>

You can load that content into a webpage:

<button id="loadHtmlBtn">Load HTML</button>
<div id="htmlResult"></div>

<script>
$("#loadHtmlBtn").on("click", function () {
    $("#htmlResult").load("message.html", function (
        response,
        status,
        xhr
    ) {
        if (status === "error") {
            $("#htmlResult").text(
                "Unable to load the HTML content."
            );
        }
    });
});
</script>

Note: The file must exist at the specified URL and be accessible to the browser. Running the example through a local web server is preferable to opening the HTML file directly.

Because .load() inserts returned HTML, only load trusted or properly sanitized content.

9. Difference Between jQuery AJAX Methods

Method Main purpose Typical response
$.ajax() Full control over a request JSON, HTML, text or other supported data
$.get() Retrieve data with GET Text, HTML or other supported response
$.post() Submit data with POST Text, JSON or other supported response
$.getJSON() Retrieve JSON data JSON
.load() Load response content into an element HTML or text

Choose the simplest method that meets your requirements. Use $.ajax() when you need more control over headers, timeouts, request configuration or response handling.

10. How to Send Data with AJAX

You can send data to the server using the data option.

$.ajax({
    url: "/api/students",
    method: "GET",
    data: {
        course: "BCA",
        page: 1
    },
    dataType: "json",

    success: function (response) {
        console.log(response);
    },

    error: function () {
        console.log("Request failed.");
    }
});

The browser sends the request to /api/students with the specified query parameters.

For a POST request, you can send form data:

$.ajax({
    url: "/api/students",
    method: "POST",

    data: {
        name: "Rahul",
        course: "BCA"
    },

    success: function (response) {
        console.log("Data submitted successfully.");
    },

    error: function () {
        console.log("Unable to submit data.");
    }
});

This code demonstrates request structure only. The endpoint must exist and accept the submitted data. Production applications should also validate input and handle authentication, authorization and CSRF protection as required by their setup.

11. How to Handle AJAX Errors

AJAX requests can fail for several reasons, including:

  • The internet connection is unavailable.

  • The server is not responding.

  • The URL is incorrect.

  • The server returns an HTTP error.

  • The response cannot be parsed in the expected format.

  • The browser blocks a cross-origin request because of CORS restrictions.

Use error handling to provide a helpful message.

$.ajax({
    url: "/api/products",
    method: "GET",
    dataType: "json",

    success: function (products) {
        console.log(products);
    },

    error: function (xhr, status, error) {
        console.error("Request status:", status);
        console.error("Error details:", error);

        $("#result").text(
            "Something went wrong. Please try again."
        );
    },

    complete: function () {
        console.log("AJAX request finished.");
    }
});

Avoid showing sensitive server error details to ordinary users. Detailed errors are more appropriate for controlled debugging or secure logs.

12. Complete Practical Project: AJAX User Loader

This mini-project loads sample user information when the user clicks a button. It demonstrates a loading message, a successful response and error handling.

Copy this code into jquery-ajax-user-loader.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>jQuery AJAX User Loader</title>

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            padding: 30px 15px;
            font-family: Arial, sans-serif;
            background: #eff6ff;
        }

        .container {
            max-width: 550px;
            margin: auto;
            padding: 25px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        }

        h1 {
            color: #1d4ed8;
        }

        button {
            padding: 12px 18px;
            border: 0;
            border-radius: 6px;
            color: white;
            background: #2563eb;
            cursor: pointer;
        }

        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        #result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            background: #f8fafc;
            overflow-wrap: anywhere;
        }

        #status {
            color: #475569;
        }
    </style>
</head>

<body>

<div class="container">

    <h1>AJAX User Loader</h1>

    <p>Click the button to load sample user data.</p>

    <button type="button" id="loadUserBtn">Load User</button>

    <p id="status" role="status" aria-live="polite"></p>

    <div id="result"></div>

</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script>
$(document).ready(function () {

    $("#loadUserBtn").on("click", function () {

        const button = $(this);

        button.prop("disabled", true);
        $("#status").text("Loading user information...");
        $("#result").empty();

        $.ajax({
            url: "https://jsonplaceholder.typicode.com/users/1",
            method: "GET",
            dataType: "json",
            timeout: 10000,

            success: function (user) {

                $("#result").empty();

                $("<h2>")
                    .text(user.name)
                    .appendTo("#result");

                $("<p>")
                    .text("Email: " + user.email)
                    .appendTo("#result");

                $("<p>")
                    .text("Phone: " + user.phone)
                    .appendTo("#result");

                $("<p>")
                    .text("Website: " + user.website)
                    .appendTo("#result");

                $("#status").text("User information loaded.");
            },

            error: function () {

                $("#status").text(
                    "Unable to load user information. Please try again."
                );

            },

            complete: function () {

                button.prop("disabled", false);

            }
        });

    });

});
</script>

</body>
</html>

Project features

  1. Loads sample user data without a full-page reload.

  2. Displays a loading message.

  3. Disables the button while the request is running.

  4. Shows the user's name, email, phone and website.

  5. Displays an error message if the request fails.

  6. Re-enables the button when the request finishes.

  7. Uses .text() to display returned values as plain text.

Important: This project uses demo data from JSONPlaceholder. Replace the URL with your own backend API when integrating AJAX into a real application.

13. jQuery AJAX Security Best Practices

When using AJAX in a production application, follow these guidelines:

  • Validate all submitted data on the server.

  • Check authentication and authorization before returning private information or modifying records.

  • Use CSRF protection for applicable state-changing requests.

  • Never place secret API keys or passwords in client-side JavaScript.

  • Avoid rendering untrusted server responses as raw HTML.

  • Use HTTPS for requests that transmit sensitive information.

  • Handle failed requests and timeouts gracefully.

  • Configure CORS on the server when cross-origin requests are required.

  • Do not rely on client-side validation alone.

Remember that AJAX does not bypass normal web security requirements. It simply provides a way for the browser to exchange data with a server.

14. Common Mistakes in jQuery AJAX

Mistake 1: Forgetting to include jQuery

If the library is not loaded, $ or jQuery may be undefined.

Solution: Confirm that the jQuery script loads successfully before your own code runs.

Mistake 2: Using the wrong URL

A request to an incorrect endpoint may return a 404 error.

Solution: Check the URL in the browser's developer tools under the Network tab.

Mistake 3: Expecting JSON when the server returns HTML

If you specify dataType: "json" but the server returns invalid JSON or an HTML error page, parsing may fail.

Solution: Confirm the actual response format and correct the server response or request configuration.

Mistake 4: Forgetting error handling

A failed request may leave the user waiting without useful feedback.

Solution: Add an error callback or a .fail() handler.

Mistake 5: Assuming POST automatically saves data

Sending a POST request does not guarantee that the server stores the submitted information.

Solution: Verify that the backend endpoint processes and saves the data successfully.

15. Frequently Asked Questions (FAQs)

Q1. What is jQuery AJAX?

jQuery AJAX is a set of jQuery methods used to exchange data with a server without reloading the entire webpage.

Q2. What does AJAX stand for?

AJAX stands for Asynchronous JavaScript and XML.

Q3. Which jQuery method is used to retrieve data?

You can use $.get(), $.getJSON() or $.ajax() with the GET method.

Q4. What is the difference between GET and POST?

GET is commonly used to retrieve data. POST is commonly used to submit data for processing or creation. Neither method alone guarantees that an operation is safe or successful.

Q5. Can jQuery AJAX send form data?

Yes. You can use $.post() or $.ajax() to submit form data to a backend endpoint.

Q6. Does AJAX require a page refresh?

No. AJAX allows JavaScript to exchange data with a server and update parts of the page without a full-page reload.

Q7. Can AJAX return JSON data?

Yes. jQuery can process JSON responses using $.getJSON() or $.ajax() with dataType: "json".

Q8. What is the difference between $.ajax() and $.get()?

$.ajax() offers more request configuration options. $.get() is a simpler shortcut for GET requests.

Q9. Is jQuery AJAX still useful?

Yes. It remains useful in existing jQuery applications and projects that use jQuery for dynamic page updates. Modern applications may also use the native Fetch API or other networking libraries.

Q10. Can jQuery AJAX be used with CodeIgniter 4?

Yes. You can send AJAX requests to CodeIgniter 4 controller routes and return JSON responses. You should also implement server-side validation, authorization and CSRF protection as appropriate.

16. jQuery AJAX Interview Questions

  1. What is AJAX?

  2. What is the full form of AJAX?

  3. How does AJAX work in jQuery?

  4. What is the purpose of $.ajax()?

  5. Explain the difference between $.get() and $.post().

  6. What is the purpose of $.getJSON()?

  7. What does the dataType option do?

  8. How do you handle errors in an AJAX request?

  9. What is the difference between synchronous and asynchronous requests?

  10. How can you send form data through AJAX?

  11. What is CORS, and how can it affect AJAX requests?

  12. How can you update an HTML element after receiving an AJAX response?

17. Practice Exercises

Try these exercises to improve your understanding:

Exercise 1: Create a button that retrieves a sample post using $.get().

Exercise 2: Retrieve a user's name and email using $.getJSON().

Exercise 3: Build a form that sends a title and description through $.post() to a demo endpoint.

Exercise 4: Create a loading indicator that disappears when an AJAX request finishes.

Exercise 5: Build a student list that fetches records from a backend API and displays them in an HTML table.

Exercise 6: Add error handling for a request that returns a 404 response.

18. Multiple-Choice Questions (MCQs)

Q1. What is the full form of AJAX?

A. Asynchronous JavaScript and XML

B. Advanced Java Application Extension

C. Automated JavaScript and XHTML

D. Asynchronous JSON Application Exchange

Correct Answer: A. Asynchronous JavaScript and XML

Q2. Which jQuery method provides the most general request configuration?

A. $.get()

B. $.ajax()

C. $.getJSON()

D. .text()

Correct Answer: B. $.ajax()

Q3. Which method is commonly used to retrieve JSON data?

A. $.getJSON()

B. $.remove()

C. $.empty()

D. $.replaceWith()

Correct Answer: A. $.getJSON()

Q4. Which HTTP method is commonly used to submit new data?

A. GET

B. HEAD

C. POST

D. OPTIONS

Correct Answer: C. POST

Q5. Which callback is used to handle a failed $.ajax() request?

A. success

B. error

C. append

D. before

Correct Answer: B. error

Q6. Does AJAX require the entire webpage to reload for every successful request?

A. Yes, always

B. No, it can update only part of the page

C. Only when using JSON

D. Only when using POST

Correct Answer: B. No, it can update only part of the page

Conclusion

jQuery AJAX helps developers build interactive webpages by exchanging data with a server without requiring a full-page reload.

You have learned how $.ajax(), $.get(), $.post(), $.getJSON() and .load() work, how to handle errors, and how to create a practical AJAX user loader.

These techniques are useful in student management systems, dashboards, search interfaces, task applications and many other web projects.

←
Post 9 of 15
→