Skip to content
Related Articles
Open in App
Not now

Related Articles

How to get server response from an AJAX request using jQuery ?

Improve Article
Save Article
Like Article
  • Last Updated : 31 Oct, 2022
Improve Article
Save Article
Like Article

In this article, we will see how we can use jQuery to get the server response to an AJAX request. To answer this question, we have to understand the jQuery ajax() method.

The jQuery ajax() method implements the basic Ajax functionality in jQuery. It communicates with the server via asynchronous HTTP requests.

Syntax:

$.ajax(url);
$.ajax(url,[options]);

 

Parameters:

  • url: A URL string to which you wish to send or get data.
  • options: Options for configuring an Ajax request. The JSON format is used to specify an options parameter. This is an optional parameter.

The table below lists all of the configuration options for Ajax requests.

Options                        Description                                                                                                                                                                                
url The URL to which the request is sent is a string.
data Data is to be transmitted to the server. It can be a JSON object, a string, or an array.
type A kind of HTTP request, such as POST, PUT, or GET. The default is GET.
success A callback function is called when an Ajax request is successful.
timeout A timeout value in milliseconds for the request.
username In response to an HTTP access authentication request, utilize this username using XMLHttpRequest.
xhr A function is s called when the XMLHttpRequest object is created.
xhrFields To set on the native XMLHttpRequest object, an object of field_Name-field_Value pairs.
statusCode A JSON object containing numeric HTTP codes and methods to be invoked when the matching code is present in the response.
accepts The content type specified in the request header, which informs the server about the sort of answer it will accept in return.
async All queries are sent asynchronously by default. To make it synchronous, set it to “false”.
beforeSend A callback function will be called before the Ajax request is issued.
cache A boolean indicating the presence of browser cache. The default value is “true”.
complete When the request is completed, a callback function is invoked.
contentType When transmitting MIME material to the server, this string contains the kind of content. The default is “application/x-www-form-urlencoded; charset=UTF-8”.
crossDomain A boolean value that indicates whether or not a request is cross-domain.
dataType The type of data you anticipate receiving from the server.
error When the request fails, a callback function is executed.
global A boolean value indicating whether or not to invoke a global Ajax request handler. The default is “true”.
headers An object containing additional header key/value pairs to deliver with the request.
ifModified Only allow the request to succeed if the response has changed since the last request. The Last-Modified header is used to do this. The default setting is “false”.
isLocal Allow the present environment to be acknowledged as local.
jsonp In a JSONP request, you can change the name of the callback function. This value will be used instead of ‘callback’ in the query string’callback=?’ section of the URL
jsonpCallback A string holding the name of the callback function for a JSONP request.
mimeType Override the XMLHttpRequest mime type with a string containing a mime type.
password In response to an HTTP access authentication request, utilize this password using XMLHttpRequest.
processData A Boolean that indicates whether or not the data supplied to the data option will be transformed into a query string. The default value is “true”.

Example 1: This example uses the ajax() method to get the text content from an external file demo.txt. In the following example, the first parameter of the ajax() function is a url from which we wish to obtain the data. The second parameter is the options parameter, which contains the success and error callback functions.

demo.txt:

Welcome To GFG

HTML code:

HTML




<!DOCTYPE html>
<html>
<head>
    <script src=
    </script>
</head>
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
  
    <h2>Click on the button to send ajax request</h2>
    <button>Send</button>
  
    <h2 id="p1"></h2>
  
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax("demo.txt", {
                    success: function (data) {
                      // Success callback function
                      $("#p1").append(data);
                    },
                    error: function (errorMessage) {
                      // Error callback
                      $("#p1").append("Error: " + errorMessage);
                    },
                });
            });
        });
    </script>
</body>
</html>


Output:

 

Example 2: The following example demonstrates how to obtain JSON data using the ajax() function. The first parameter in the following example is a request url that will return JSON data. We have mentioned the dataType option in the options argument. The dataType option defines the kind of response data, which in this case is JSON. We have also defined error and success callback functions.

demo.json:

{
  "name": "Vishal Kumar", 
  "age" : "22", 
  "gender": "Male" 
}

HTML code:

HTML




<!DOCTYPE html>
<html>
<head>
    <script src=
    </script>
  
    <style>
        #output {
            background-color: rgb(205, 228, 30);
            width: fit-content;
        }
    </style>
</head>
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
  
    <h2>Click on the button to send ajax request</h2>
  
    <button>Send</button>
  
    <div id="output"></div>
  
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax("demo.json", {
                    success: function (data) {
                      // success callback function
                      $("#output").append("<p> Name: " + data.name + "</p>");
                      $("#output").append("<p>Age : " + data.age + "</p>");
                      $("#output").append("<p>Gender: " + data.gender + "</p>");
                    },
                    error: function (errorMessage) {
                      // error callback
                      $("#output").append("Error: " + errorMessage);
                    },
                });
            });
        });
    </script>
</body>
</html>


Output:

 


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!