Skip to content
Related Articles
Open in App
Not now

Related Articles

Which parameters are being used for the jQuery Ajax method ?

Improve Article
Save Article
  • Last Updated : 19 Jul, 2022
Improve Article
Save Article

In this article, we will see the parameters that are used in the jQuery Ajax method along with understanding their implementations through the illustrations.

The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Generally, the ajax() method is used in all the required jQuery AJAX methods, which are mostly used for requests & which is not being used by the other methods.

Syntax:

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

Parameter Values: The list of possible values are given below:

  • type: It is used to specify the type of request.
  • url: It is used to specify the URL to send the request to.
  • username: It is used to specify a username to be used in an HTTP access authentication request.
  • xhr: It is used for creating the XMLHttpRequest object.
  • async: Its default value is true. It indicates whether the request should be handled asynchronous or not.
  • beforeSend(xhr): It is a function that is to be run before the request is sent.
  • dataType: The data type expected of the server response.
  • error(xhr, status, error): It is used to run if the request fails.
  • global: Its default value is true. It is used to specify whether or not to trigger global AJAX event handles for the request.
  • ifModified: Its default value is false. It is used to specify whether a request is only successful if the response has changed since the last request.
  • jsonp: A string overriding the callback function in a jsonp request.
  • jsonpCallback: It is used to specify a name for the callback function in a jsonp request.
  • cache: Its default value is true. It indicates whether the browser should cache the requested pages.
  • complete(xhr, status): It is a function that is to be run when the request is being finished.
  • contentType: Its default value is: “application/x-www-form-urlencoded” and it is used when data send to the server.
  • context: It is used to specify the “this” value for all AJAX-related callback functions.
  • data: It is used to specify data to be sent to the server.
  • dataFilter(data, type): It is used to handle the raw response data of the XMLHttpRequest.
  • password: It is used to specify a password to be used in an HTTP access authentication request.
  • processData: Its default value is true. It is used to specify whether or not data sent with the request should be transformed into a query string.
  • scriptCharset: It is used to specify the charset for the request.
  • success(result, status, xhr): It is to be run when the request succeeds.
  • timeout: It is the local timeout for the request. It is measured in terms of milliseconds.
  • traditional: It is used to specify whether or not to use the traditional style of param serialization.

The various parameters can be understood by implementing the following examples. Few are given for reference but the developer can change code as per the need.

Example 1: The following code demonstrates the ajax() method with “url” and “context” parameters which adds a class to the body document for changing the background color by using CSS background-color property. The class is added by using the jQuery addClass() method. The value of “url” will be the “test.html” file provided below the code.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
    <meta name="viewport" content=
          "width=device-width, initial-scale=1">
    <script type="text/javascript" src=
    </script>
    <style>
        .bgClass {
            background-color: grey;
        }
    </style>
</head>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h3>Ajax methods with parameters</h3>
    <p>This is document body with paragraph</p>
    <script>
        $.ajax({
            url: "test.html",
            context: document.body
        }).done(function() {
            $(this).addClass("bgClass");
        });
    </script>
</body>
</html>


test.html: This file is used in the above file.

<html>
   <p>hello world</p>
</html>

Output:

 

Example 2: The following code demonstrates the ajax() method with “success” and “error” parameters.  The value of “url” will be the “sample.html” file provided below the code.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <script>
        $(document).ready(function () {
            $("#btnID").click(function () {
                $.ajax({
                    url: "sample.txt", 
                    success: function (output) {
                        $("#divID").html(output);
                    },
                    error: function () {
                        alert("Ajax error!");
                    }
                });
            });
        });
    </script>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <h3>Ajax with parameters</h3>
    <div id="divID">
        <p id="paraID">
            This is paragraph. Ajax is an acronym 
            for Asynchronous Javascript and XML.<br>
            It is used to communicate with the 
            server without refreshing<br>the web 
            page and thus increasing the user
            experience and better performance.
        </p>
    </div>
    <button id="btnID">
        Change the paragraph content
    </button>
</body>
</html>


sample.txt: This file is used in the above file.

This is changed paragraph for the HTML document.<br>
There are no such pre-requisites required to understand the latter portion of the article.<br>
Only the basic knowledge of HTML, CSS, and Javascript are good to go.

Output:

 

Example 3: The following code demonstrates the ajax() method with “contentType”, “dataType” and beforeSend() method parameters.  The value of “url” will be the “url.json” file provided below the code.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>jQuery ajax beforeSend() function </title>
    <meta charset="utf-8">
    <script type="text/javascript" src=
    </script>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <h3>jQuery ajax beforeSend() function</h3>
    <button id="buttonID">
        Send the request using ajax beforeSend()
    </button>
    <br>
    <p id="paraID" style=""> </p>
  
    <script type="text/javascript">
        $(document).ready(function () {
  
            $('#buttonID').click(function () {
                // url
                var request = $.ajax({
                    url: 'url.json',
                    contentType: 'application/json',
                    dataType: 'json',
                    beforeSend: function (jqXHR) {
                        jqXHR.overrideMimeType("application/json");
                        $('#paraID').append(
          '<p><b> The beforeSend() method is called.<b></p>');
                    }
                });
                request.success(function (data, status, jqXhr) {
                    $('#paraID').append('<p><b> The json data : </p></b>');
                    $('#paraID').append('<p><b> Date :</b> '
                        + data.date
                        + '</p>');
                    $('#paraID').append('<p><b> Name :</b> '
                        + data.name
                        + '</p>');
                    $('#paraID').append('<p><b> Time: </b>'
                        + data.time
                        + '</p>');
                });
                request.error(function (jqXhr, textStatus, errorMessage) {
                    $('#paraID').append(
                        '<p><b> The request status:</b> '
                        + status
                        + '</p>');
                    $("#paraID").append("The status is : " + textStatus);
                });
            });
        });
    </script>
</body>
</html>


url.json: This JSON file is used in the above file.

{
   "date": "07-15-2022",
   "name": "Ajax learning",
   "time": "11:32:10 AM"
}

Output:

 

Example 4: The following code demonstrates the ajax() method with “contentType”, “dataType” and “jsonpCallback” parameters.  The value of “url” will be the “urljsonP.json” file provided below the code. Set the  jsonpCallback: ‘JSONPResponse’ property where “JSONPResponse” is mentioned in the JSON file as shown below.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
    <meta name="viewport" content=
    "width=device-width, initial-scale=1">
  
    <script type="text/javascript" src=
    </script>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3>Ajax methods with parameters</h3>
    <p>This is document body with paragraph</p>
    <script>
        $.ajax({
            url: "urljsonP.json",
            dataType: "jsonp",
            type: "POST",
            jsonpCallback: 'JSONPResponse',
            contentType: "application/json; charset=utf-8",
            success: function (result, status, xhr) {
                console.log(result);
            },
            error: function (xhr, status, error) {
                console.log("Result: " + status + " "
                    + error + " " + xhr.status 
                    + " " + xhr.statusText)
            }
        });
    </script>
</body>
</html>


urljsonP.json: This JSON file is used in the above file.

JSONPResponse( {
  "id":  1,
  "name": "accessory",
  "items": [ "book", "pen" ]
})

Output:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!