0

I would like to have a WordPress text widget with a javascript that would populate the widget with text from some .txt file (this is to allow dynamic content on a cached page by allowing me to update that text file with new HTML content).

I found this thread and tried the following code, which did not work:

<script type="text/javascript">     
function read(textFile){
    var xhr=new XMLHttpRequest;
    xhr.open('GET',textFile);
    xhr.onload=show;
    xhr.send()
}

function show(){
    var pre=document.createElement('pre');
    pre.textContent=this.response;
    document.body.appendChild(pre)
}

read('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
</script>  

Any suggestions on how to fix it?

3
  • What is your show() function doing? Commented Dec 17, 2016 at 22:33
  • This worked just fine in jsfiddle for me ... Possibly there is something else that's obstructing. Commented Dec 17, 2016 at 22:41
  • Where do you call read? Is the <script> element at Question within <head> element? Is document.body defined? Have you tried calling read within window load event handler? Commented Dec 17, 2016 at 22:43

1 Answer 1

1

Do you know Javascript or are you just hoping for a copy and paste solution? Perhaps try reworking this code here:

function getStuff(url) {
  var xhttp, jsonData, parsedData;

  // check that we have access to XMLHttpRequest
  if(window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
  } else {
    // IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

     // get the data returned from the request...
     jsonData = this.responseText;
     // ...and parse it
     parsedData = JSON.parse(jsonData);

     // return the data here
     // if the data you're returning is an object
     // you need to know the endpoints
     // for example, if there was a username,
     // you might return parsedData.username
     var something = parsedData.endpoint;
     // debug / test
     console.log(something);

     var elementToShowStuffIn = document.getElementById('theIDOfTheElement');
     elementToShowStuffIn.innerHTML = something;


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

getStuff('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');

Yes, this works. Just replace this line here: var something = parsedData.foo.bar;

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

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.