AJAX Example code showing XML response in a DIV tag

This is an example code which demonstrates how we can show the response from a XML file to the DIV tag.

<html>
<head>
<title>Using responseText with innerHTML</title>
 
<script type="text/javascript">
var xmlHttp;
 
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}
 
function startRequest() {
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", "response.xml", true);
    xmlHttp.send(null);
}
 
function handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            document.getElementById("results").innerHTML = xmlHttp.responseText;
        }
    }
}
</script>
</head>
 
<body>
    <form action="#">
        <input type="button" value="Search"
                onclick="startRequest();"/>
    </form>
    <div id="results"></div>
</body>
</html>


Notice the line in Javascript.

document.getElementById("results").innerHTML = xmlHttp.responseText;

This is doing all the magic for you.

Below are the contents of reponse.xml

<table border="1">
    <tbody>
        <tr>
            <th>My Name</th>
            <th>Location</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>John</td>
            <td>NH</td>
            <td>20</td>
        </tr>
        <tr>
            <td>Peter</td>
            <td>CA</td>
            <td>25</td>
        </tr>
        <tr>
            <td>Hary</td>
            <td>NC</td>
            <td>33</td>
        </tr>
    </tbody>
</table>


Keep both the files in the same directory on server and run it.

2 Post Comment

Anonymous said...

This is helpful. Thx

ch2online said...

Cool blog you got here. It would be great to read more concerning this matter.

Post a Comment

Search Web......