Computers & ProgrammingAJAXFrontend Development

AJAX XMLHttpRequest responseText Data

The XMLHttpRequest object is used to send and receive data between a web browser and web server. In this article, we are going to look at how to receive data from a web server.

To receive the response from a web server, you can use the responseText or responseXML property of the XMLHttpRequest object. In this article, we are going to look at the responseText in more detail.

HTML Example

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function loadAjax() {
            var xhr = false;
            if (window.XMLHttpRequest) {
                // IE7+, Firefox, Chrome, Opera, Safari
                xhr = new XMLHttpRequest();
            } 
            else {
                // IE5/IE6
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (xhr) {
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        document.getElementById("div1").innerHTML = xhr.responseText;
                    }
                }
                xhr.open("GET", "/demo/ajax_load.txt", true);
                xhr.send(null);
            }
        }
    </script>
</head>
<body>
    <img id="img1" onclick="loadAjax()" src="go.png" /> ; 
    <div id="div1"> <!-- Some Content --> </div>
</body>
</html>

Syntax

xhr.responseText;

responseText Property

If the response you receive from the web server is not XML, then use the responseText property. The responseText property returns the response as a string.

document.getElementById("div1").innerHTML = xhr.responseText;

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top