3

I was trying to read a txt file and display its content in my web page, since its content changes over time, I want to update it periodically. Here is my code, it displays the content at first, but it won't change after I changed the file's content. Any suggestions? Thanks.

<script type="text/javascript">
        setTimeout(read(),3000);
    function read(){
    setTimeout(jQuery.get('now.txt',function(data){
    document.write(data);}),1000);
    }
</script>

3 Answers 3

3

Nearly there. Change:

setTimeout('read', 3000);
           ^^^^^ here

and here:

function read(){
    jQuery.get('now.txt',function(data){document.write(data);});
}

If you want it to refresh every 3 seconds use setInterval

Documentation:

Sign up to request clarification or add additional context in comments.

2 Comments

I tried with setInterval(read,3000); and it works! The problem right now is that it keeps adding the contents at the end. Is there anyway to wipe former data and just display the current content?
add <div id="container"></div> to your HTML and change document.write(data) to $('#container').html(data);
1

the function name does not need to be closed. It also does not need to be a string.

change this

setTimeout(read(),3000);

to this

setTimeout(read, 3000);

Comments

1

Your ajax results might be cached try setting $.ajaxSetup({cache: false}). Also I'm not sure what you are trying to achieve with the setTimeouts, are you trying to load the page after 3+1 seconds?

<script type="text/javascript">
    $.ajaxSetup({cache: false})
    setTimeout(read, 3000);
    function read(){
        jQuery.get('now.txt',function(data){
        document.write(data);});
    }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.