Open In App

jQuery ajax() Method

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The jQuery ajax() method is used to perform asynchronous HTTP requests, allowing you to load data from a server without reloading the webpage. It provides a flexible way to interact with remote servers using GET, POST, or other HTTP methods, supporting various data formats.

Syntax:

$.ajax({name:value, name:value, ... })

Parameters: The list of possible parameter that can be passed to an Ajax request are listed below:

PropertyDescription
typeSpecifies the request type as POST or GET.
urlSpecifies the URL to send the request to.
usernameSpecifies the username for HTTP access authentication.
xhrCreates the XMLHttpRequest object.
asyncDefault is true. Specifies if the request is asynchronous.
beforeSend(xhr)A function executed before the request is sent.
dataTypeExpected data type of the server response.
error(xhr, status, error)A function executed if the request fails.
globalDefault is true. Specifies whether to trigger global AJAX events for the request.
ifModifiedDefault is false. A request is successful only if the response has changed.
jsonpOverrides the callback function for JSONP requests.
jsonpCallbackSpecifies a name for the callback function in a JSONP request.
cacheDefault is true. Indicates whether the browser should cache requested pages.
complete(xhr, status)A function that runs when the request is finished.
contentTypeDefault is "application/x-www-form-urlencoded". Specifies content type of data sent.
contextSpecifies the “this” value for all AJAX-related callbacks.
dataSpecifies data to be sent to the server.
dataFilter(data, type)Handles raw response data from the XMLHttpRequest.
passwordSpecifies a password for HTTP access authentication.
processDataDefault is true. Specifies if the data should be transformed into a query string.
scriptCharsetSpecifies the charset for the request.
success(result, status, xhr)Runs when the request succeeds.
timeoutLocal timeout for the request, measured in milliseconds.
traditionalSpecifies whether to use the traditional style of parameter serialization.

Example 1: In this example we use jQuery’s ajax() method to load content from “geeks.txt” into an <h3> element when the button is clicked. The request is handled asynchronously, displaying the text on success.

<!DOCTYPE html>
<html>

<head>
    <title>
        jQuery ajax() Method
    </title>

    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>

    <script>
        $(document).ready(function () {
            $("li:parent").css("background-color", "green");
        });
    </script>
</head>

<body style="text-align:center;">

    <h1 style="color:green">
        GeeksForGeeks
    </h1>

    <h2>
        jQuery ajax() Method
    </h2>

    <h3 id="h11"></h3>

    <button>Click</button>

    <!-- Script to use ajax() method to
        add text content -->
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax({
                    url: "geeks.txt",
                    success: function (result) {
                        $("#h11").html(result);
                    }
                });
            });
        });
    </script>
</body>

</html>

geeks.txt

"hello geeks !"

Output:

jquery-70

Example 2: In this example we use jQuery’s ajax() method to fetch content from “geeks.txt” and display it in an <h3> element when the button is clicked. It includes error handling with a console log.

<!DOCTYPE html>
<html>

<head>
    <title>jQuery ajax() Method</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
</head>

<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksForGeeks
    </h1>
    <h2>jQuery ajax() Method</h2>
    <h3 id="h11"></h3>
    <button>Click</button>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax({
                    url: "geeks.txt",
                    success: function (result) {
                        $("#h11").html(result);
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                    }
                });
            });
        });
    </script>
</body>

</html>

Output:

geeksoutput

jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.

jQuery ajax() Method – FAQs

How do you make a GET request using jQuery ajax()?

Use $.ajax({ type: ‘GET’, url: ‘your-url’, success: function(result) { /* handle success */ } });.

How can you handle errors in jQuery ajax()?

Use the error option: $.ajax({ url: ‘your-url’, error: function(xhr, status, error) { /* handle error */ } });.

What are the common options used in jQuery ajax()?

Common options include url, type, data, dataType, success, error, and complete.

How to send data with a jQuery ajax() POST request?

Use the data option: $.ajax({ type: ‘POST’, url: ‘your-url’, data: { key: ‘value’ } });.

How to specify a timeout for a jQuery ajax() request?

Use the timeout option: $.ajax({ url: ‘your-url’, timeout: 5000 }); // timeout in milliseconds.

Can you cache results in jQuery ajax() requests?

Yes, use the cache option: $.ajax({ url: ‘your-url’, cache: true });.



Similar Reads

three90RightbarBannerImg