Search code examples
javascripthtmlajaxxmlhttprequestserver-side

Using Ajax to change the inner content of a div


I am a beginner at Ajax, and I have this html code that is meant to change the inner content of a div by using xmlhttprequest to request different html addresses and put their contents in a div. What am I doing wrong? Here is the code:

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <script type="text/javascript">
        var xmlhttp= null;
        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }else{
            alert("You must be using a different browser.");
        }

        function makeRequest(serverPage,objID){

            var obj = document.getElementById(objID);
            xmlhttp.open("GET",serverPage);
            xmlhttp.onreadystatechange = function(){
                if(xmlhttp.readyState == 4 && xmlhttp.status == 100){
                    obj.innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.send(null);
        }
    </script>
</head>
<body onload="makeRequest ('content1.html','hw')">
    <div align="center">
        <h1>My Webpage</h1>
        <a href="content1.html" onclick="makeRequest('content1.html','hw'); return false;"> Page1</a> | <a href="content2.html" onclick="makeRequest('content2.html','hw'); return false;"> Page2</a> | <a href="content3.html" onclick="makeRequest('content3.html','hw'); return false;"> Page3</a> | <a href="content4.html" onclick="makeRequest(content4.html,hw); return false;"> Page4</a>
        <div id = "hw"></div>
</body>


Solution

  • Generally, this looks OK to me.

    However the xmlhttp.status == 100 check looks suspicious.

    100 is an unusual HTTP status code. Typically web servers return 200 ("OK") on a successful request.

    Try replacing the status == 100 check with status == 200.

    For reference,please see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html