I am trying to fetch the list of words from an external .txt file and put them into a javascript array, after which to pull a random word from that array and insert it into a paragraph element.
The words.txt:
"word1", "word2", "word3", "word4", "word5", "word6"
HTML and Javascript:
<div><p id="word"></p></div>
<script>
var wordList = fetch("/js/words.txt");
var words = Array(wordList);
const randomWord = Math.floor(Math.random()*words.length);
function word() { document.getElementById("word").innerHTML = randomWord; }
</script>
When I load the webpage, it’s empty. There is no words in the paragraph element. What’s the issue?
>Solution :
The issue is that you’re not handling the asynchronous nature of the fetch function correctly. The fetch function returns a Promise that resolves to the response of the HTTP request. You need to handle this Promise and extract the text content from the response before you can use it.
you can do it like this:
`
<div><p id="word"></p></div>
<script>
fetch('/js/words.txt")
.then(response => response.text())
.then(text => {
var wordList = text.split(", ");
const randomIndex = Math.floor(Math.random() * wordList.length);
const randomWord = wordList[randomIndex];
document.getElementById("word").innerHTML = randomWord;
})
.catch(error => console.error('Error fetching words:', error));
</script>
`
This code fetches the content of the "words.txt" file, splits it into an array of words using split(", "), generates a random index to pick a word from the array, and finally displays the random word in the paragraph element.
Make sure to adjust the file path "/js/words.txt" to the correct location of your "words.txt" file. Additionally, ensure that your server is configured to serve ".txt" files correctly.