Ajax XMLHttpRequest responseText Data

Tuesday, July 24, 2012

The XMLHttpRequest object is used to send and receive data with 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;


responseText Example



click here
Click the icon to load text data!


Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

HTML CSS and JavaScript Editor Ajax for Dummies The Complete Reference Ajax