views:

75

answers:

4

Hello. I'm doing something very simple, and yet it's not working.. maybe I'm missing something.

I need to read a text file, through ajax, and into a div. I can easily write to the file through ajax, but not read. Here is what I have:

function ajaxLoader(url)
{
if(document.getElementById)
{
var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new
XMLHttpRequest();
}
if(x)
    {
x.onreadystatechange = function() 
     {
if(x.readyState == 4 && x.status == 200) 
      {
       el = document.getElementById('content');
       el.innerHTML = x.responseText;
      }
     }

x.open("GET",url, true);
x.send(null);
}
}

<a class="blocklink" href="#" id="readg" onclick="ajaxLoader('guestBook.txt')">Read The Guestbook</a></p>

<div id="content" style="width:600px;">

I've been stuck on this all day. I can use all of the same code, and output a regular html file to the div, but not this .txt file. The txt file has all of the read write privileges it needs. Thanks!

Marcus

A: 

Try to remove that if(document.getElementById)

Can you alert your .responseText property? It works using a synchronous pattern?

Rubens Farias
it seems to go through the if statements. When I alert x.responsetype, I get nothing... it's blank... I'm not good with ajax, so not sure what that is about. Also not sure about the synchronous patter. Any ideas?
Marcus
A: 

Your ajaxLoader function should return false so that the link that is clicked is not followed.

Mark Stewart
That doesn't help unless you also return the function result in the click event.
Guffa
A: 

If you are running the code locally, you will get the status 0 instead of status 200. To handle both, you can use:

if (x.readyState == 4 && (x.status == 0 || x.status == 200))

Also, when you click the link, the link will be followed as you haven't cancelled it. As the href is "#" it will go to the top of same page, but it can still cause problems. (One side effect is that the page will scroll to the top when you press the link.) Cancel the link from being followed by returning false from the click event:

onclick="ajaxLoader('guestBook.txt');return false;"
Guffa
alright, so I added the return false, and it still doesn't work. Any ideas?
Marcus
also, I threw an alert in that readystate and it hits it
Marcus
A: 

Figured it out.. I never cleared the cache... the CACHE WINS AGAIN!

Marcus