XMLHttpRequest() keeps returning back undefined

Viewed 247

I am attemping to do the tutorial from MDN called 'XMLHttpRequest'. However, the request.open('GET', url) keeps returning back undefined when I try to use it on a txt file in the local directory. I consoled logged the url and request and they come back fine. Below is my code along with the txt file I am trying to use for this project which is in the local directory using VS code as an editor along with the live servor Port: 5500.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>Ajax starting point</title>

    <style>
        html,
        pre {
            font-family: sans-serif;
        }
        
        body {
            width: 500px;
            margin: 0 auto;
            background-color: #ccc;
        }
        
        pre {
            line-height: 1.5;
            letter-spacing: 0.05rem;
            padding: 1rem;
            background-color: white;
        }
        
        label {
            width: 200px;
            margin-right: 33px;
        }
        
        select {
            width: 350px;
            padding: 5px;
        }
    </style>
    <!--[if lt IE 9]>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
    <![endif]-->
</head>

<body>
    <h1>Ajax starting point</h1>

    <form>
        <label for="verse-choose">Choose a verse</label>
        <select id="verse-choose" name="verse-choose">
            <option>Verse 1</option>
            <option>Verse 2</option>
            <option>Verse 3</option>
            <option>Verse 4</option>
        </select>
    </form>

    <h2>The Conqueror Worm, <em>Edgar Allen Poe, 1843</em></h2>

    <pre>

    </pre>

    <script>
        const verseChoose = document.querySelector('select');
        const poemDisplay = document.querySelector('pre');

        verseChoose.onchange = function() {
            const verse = verseChoose.value;
            updateDisplay(verse);
        };

        function updateDisplay(verse) {
            verse = verse.replace(" ", "");
            verse = verse.toLowerCase();
            let url = verse + '.txt';
            let request = new XMLHttpRequest();
            console.log(url);
            console.log(request);
            request.open('GET', url);
            console.log(request.open('GET', url))
            request.responseType = 'text';

            request.onload = function() {
                poemDisplay.textContent = request.response;
                request.send();
            };
        }
        updateDisplay('Verse 1');
        verseChoose.value = 'Verse 1';
    </script>
</body>

</html>

verse1.txt (in local directory)

Lo! 'tis a gala night
   Within the lonesome latter years!
An angel throng, bewinged, bedight
   In veils, and drowned in tears,
Sit in a theatre, to see
   A play of hopes and fears,
While the orchestra breathes fitfully
   The music of the spheres.
Mimes, in the form of God on high,
   Mutter and mumble low,
And hither and thither fly-
   Mere puppets they, who come and go
At bidding of vast formless things
   That shift the scenery to and fro,
Flapping from out their Condor wings
   Invisible Woe!
3 Answers

Simply move the send call in the correct position as follows:

        function updateDisplay(verse) {
            verse = verse.replace(" ", "");
            verse = verse.toLowerCase();
            let url = verse + '.txt';
            let request = new XMLHttpRequest();
            console.log(url);
            console.log(request);
            request.open('GET', url);
            console.log(request.open('GET', url))
            request.responseType = 'text';
            request.onload = function() {
                poemDisplay.textContent = request.response;
            };
            request.send();
        }

It looks like you are not sending the request at the right time. Let me know if this works:

function updateDisplay(verse) {
    verse = verse.replace(" ", "");
    verse = verse.toLowerCase();
    let url = verse + '.txt';
    let request = new XMLHttpRequest();
    console.log(url);
    console.log(request);
    request.open('GET', url);
    console.log(request.open('GET', url))
    request.responseType = 'text';
    request.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
          poemDisplay.textContent = request.response;
       };
    request.send();
}

"request.send();" should be before "request.onload", because "send" is "question" and "onload" is "answer".

var request = new XMLHttpRequest();
    request.open('GET', url);
    request.responseType = 'text';
    request.send();
    request.onload = function() 
    {   
        poemDisplay.textContent = request.response;
    };
Related