views:

35

answers:

2

I am trying to learn how to use ajax and i cant seem to figure out why the below code does not work. All it does is first create a valid XMLHttpRequest object when the page firsts loads and then inserts some text into a section of the pages div area.

Demo.js

var ajaxRequest;  // The variable that makes Ajax possible!
function newRequest()
{
    try
    {
        ajaxRequest = new XMLHttpRequest();
    ..
    }    
}

I call this by using the following:

Index.html

<script src="Demo.js" type="text/javascript"></script>
</head>
<body onload="newRequest()">
    <div class="page_Disp">
    </div>

I then try to load some text from a file into the page using the following JS Function:

Demo.js

function openPage()
{
    ajaxRequest.onreadystatechange=function()
    {
        if (ajaxRequest.readyState==4 && ajaxRequest.status==200)
        {
            document.getElementById("page_Disp").innerHTML=ajaxRequest.responseText;
            ajaxRequest.open("GET","ajax_info.txt",true);
            ajaxRequest.send();
        }
    }
}

The above is called using the following html code:

<a onclick="openPage()">Load TXT</a>

Can anyone see the problem that causes the script to not load and insert the data from the .txt into the section?

+2  A: 

You are using a class on the element:

<div class="page_Disp">

But are trying to get it by id:

document.getElementById("page_Disp")

So you need to change it to an id to get it populated:

<div id="page_Disp">
Nick Craver
+1  A: 

I would expect your Demo.js to look like this

function openPage()
{
    ajaxRequest.onreadystatechange=function()
    {
        if (ajaxRequest.readyState==4 && ajaxRequest.status==200)
        {
            document.getElementById("page_Disp").innerHTML=ajaxRequest.responseText;
        }
    }
    ajaxRequest.open("GET","ajax_info.txt",true);
    ajaxRequest.send();
}

Otherwise the ajaxRequest will never get to send the request, because it was inside the code that responded to the request.

Codemwnci
Ah, thanks a lot for that. I didnt notice that.
Ian Ball