Open In App

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

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how we can use jQuery to get the server response to an AJAX request. 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 post or get the 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                                                                                                                                                                                
urlThe URL to which the request is sent is a string.
dataData is to be transmitted to the server. It can be a JSON object, a string, or an array.
typeA kind of HTTP request, such as POST, PUT, or GET. The default is GET.
successA callback function is called when an Ajax request is successful.
timeoutA timeout value in milliseconds for the request.
usernameIn response to an HTTP access authentication request, utilize this username using XMLHttpRequest.
xhrA function is s called when the XMLHttpRequest object is created.
xhrFieldsTo set on the native XMLHttpRequest object, an object of field_Name-field_Value pairs.
statusCodeA JSON object containing numeric HTTP codes and methods to be invoked when the matching code is present in the response.
acceptsThe content type specified in the request header, which informs the server about the sort of answer it will accept in return.
asyncAll queries are sent asynchronously by default. To make it synchronous, set it to “false”.
beforeSendA callback function will be called before the Ajax request is issued.
cacheA boolean indicating the presence of browser cache. The default value is “true”.
completeWhen the request is completed, a callback function is invoked.
contentTypeWhen transmitting MIME material to the server, this string contains the kind of content. The default is “application/x-www-form-urlencoded; charset=UTF-8”.
crossDomainA boolean value that indicates whether or not a request is cross-domain.
dataTypeThe type of data you anticipate receiving from the server.
errorWhen the request fails, a callback function is executed.
globalA boolean value indicating whether or not to invoke a global Ajax request handler. The default is “true”.
headersAn object containing additional header key/value pairs to deliver with the request.
ifModifiedOnly 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”.
isLocalAllow the present environment to be acknowledged as local.
jsonpIn 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
jsonpCallbackA string holding the name of the callback function for a JSONP request.
mimeTypeOverride the XMLHttpRequest mime type with a string containing a mime type.
passwordIn response to an HTTP access authentication request, utilize this password using XMLHttpRequest.
processDataA 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: The below example uses the ajax() method to get the text content from an external file demo.txt.

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>

                    

demo.txt:

Welcome To GFG

Output:

Example 2: The following example demonstrates how to obtain JSON data using the ajax() function.

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>

                    

demo.json:

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

Output:



Next Article

Similar Reads