How Can I Get JS AJAX Server Response With Example

admin_img Posted By Bajarangi soft , Posted On 08-10-2020

The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.so today we are discuss how to get ajax server response.

How Can I Get JS AJAX Server Response With Example

The onreadystatechange Property

The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a function to be executed when the readyState changes.

The status property and the statusText property holds the status of the XMLHttpRequest object.
 

Property Description
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
403: "Forbidden"
404: "Page not found"
For a complete list go to the Http Messages Reference
statusText Returns the status-text (e.g. "OK" or "Not Found")


The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

Example(1)

<script>
    function loadDoc() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("demo").innerHTML =
                    this.responseText;
            }
        };
        xhttp.open("GET", "demo_json.txt", true);
        xhttp.send();
    }
</script>
 

The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.



Using a Callback Function

A callback function is a function passed as a parameter to another function.

If you have more than one AJAX task in a website, you should create one function for executing the XMLHttpRequest object, and one callback function for each AJAX task.

The function call should contain the URL and what function to call when the response is ready.

Example(2)

<button class="btn btn-success" type="button" onclick="loadDoc1('demo_json.txt', myFunction)">Change Content</button>
<script>
  
    function loadDoc1(url, cFunction) {
        var xhttp;
        xhttp=new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                cFunction(this);
            }
        };
        xhttp.open("GET", url, true);
        xhttp.send();
    }
    function myFunction(xhttp) {
        document.getElementById("demo1").innerHTML =
            xhttp.responseText;
    }
</script>

 

Server Response Properties

Property Description
responseText get the response data as a string
responseXML get the response data as XML data


Server Response Methods

Method Description
getResponseHeader() Returns specific header information from the server resource
getAllResponseHeaders() Returns all the header information from the server resource


The responseText Property

The responseText property returns the server response as a JavaScript string, and you can use it accordingly:

Example(3)

<button class="btn btn-success" type="button" onclick="loadDoc()">Change Content</button>

<script>
    function loadDoc() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("demo").innerHTML =
                    this.responseText;
            }
        };
        xhttp.open("GET", "demo_json.txt", true);
        xhttp.send();
    }
</script>


The responseXML Property

The XMLHttpRequest object has an in-built XML parser.

The responseXML property returns the server response as an XML DOM object.

Using this property you can parse the response as an XML DOM object:

Example(4)

<p id="demo"></p>

<script>
    var xhttp, xmlDoc, txt, x, i;
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            xmlDoc = this.responseXML;
            txt = "";
            x = xmlDoc.getElementsByTagName("ARTIST");
            for (i = 0; i < x.length; i++) {
                txt = txt + x[i].childNodes[0].nodeValue + "<br>";
            }
            document.getElementById("demo").innerHTML = txt;
        }
    };
    xhttp.open("GET", "demo.xml", true);
    xhttp.send();
</script>

 

You will learn a lot more about XML DOM in the DOM chapters of this tutorial.



The getAllResponseHeaders() Method

The getAllResponseHeaders() method returns all header information from the server response.

Example(5)

<p id="demo"></p>

<script>
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML =
                this.getAllResponseHeaders();
        }
    };
    xhttp.open("GET", "demo_json.txt", true);
    xhttp.send();
</script>


The getResponseHeader() Method

The getResponseHeader() method returns specific header information from the server response.

<p>Last modified: <span id="demo"></span></p>

<script>
    var xhttp=new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML =
                this.getResponseHeader("Last-Modified");
        }
    };
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send();
</script>


Complete Code For Getting JS AJAX Server Response With Example

<!DOCTYPE html>
<html>
<head>
    <title>How Can I Get JS AJAX Server Response With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 id="color" style="color: tomato">How Can I Get JS AJAX Server Response With Example</h1>
    </div>
    <div class="well">
        <h2 id="demo">Let AJAX change this text.</h2>
        <h2 id="demo1">Let AJAX change this text.</h2>
        <h2>Last modified: <span id="demo2"></span></h2>

        <button class="btn btn-success" type="button" onclick="loadDoc()">Change Content</button>
        <button class="btn btn-success" type="button" onclick="loadDoc1('demo_json.txt', myFunction)">Change Content</button>

        <script>
            function loadDoc() {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) {
                        document.getElementById("demo").innerHTML =
                            this.responseText;
                    }
                };
                xhttp.open("GET", "demo_json.txt", true);
                xhttp.send();
            }

            function loadDoc1(url, cFunction) {
                var xhttp;
                xhttp=new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) {
                        cFunction(this);
                    }
                };
                xhttp.open("GET", url, true);
                xhttp.send();
            }
            function myFunction(xhttp) {
                document.getElementById("demo1").innerHTML =
                    xhttp.responseText;
            }

            var xhttp=new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("demo2").innerHTML =
                        this.getResponseHeader("Last-Modified");
                }
            };
            xhttp.open("GET", "demo_json.txt", true);
            xhttp.send();
        </script>
    </div>
</div>
</body>
</html>

Related Post