Search code examples
javascriptxmlhttprequest

XMLHttpRequest Getting old values


I'm trying to read a file with XMLHttpRequest, get its content and add it to a chart from chart.js.

function loadFile() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'file.txt');
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      val = xhr.responseText;
    }
  }
  xhr.send();
}

file.txt :

123

I have a button, when I click on it it adds val to an array (for my chart).It works, but val does not changes when the file is getting changed by the server. So it keeps adding '123' while the content of file.txt has changed.


Solution

  • Answer is in comment from Paulo Diogo:

    have you tried check the cache? Like: Press CTRL + F5 before fire another request. Or add xhr.setRequestHeader("Cache-Control", "max-age=0");

    I added xhr.setRequestHeader("Cache-Control", "max-age=0"); in my button click.