The XMLHttpRequest function consistently comes back as undefined

Currently, I am working on the MDN tutorial about 'XMLHttpRequest'. Unfortunately, when trying to use request.open('GET', url) with a txt file from my local directory, it is returning undefined. I have checked both the url and request in the console log, and they appear to be correct. Below you can find my code along with the txt file I am attempting to utilize for this project. I am using VS Code as an editor and running it through a live server on 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!

Answer ā„–1

To correctly position the send call, simply follow these steps:

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

Answer ā„–2

It appears that the timing of your request may be off. Please try using this updated function:

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

Answer ā„–3

"It is recommended to place the line "request.send();" before "request.onload" in the code snippet below. This is because "send" represents a "question" and "onload" represents an "answer".

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulate JSON data structure with JavaScript

The initial JSON data: { "data": { "count_at_hub": [ { "hub": "A", "date": "", "size": "1", "count": 141 }, { "hub": "A", "date": "", "size": " ...

saving a JSON element in a JavaScript array

Currently, I am utilizing AJAX to fetch data from a database using PHP and then converting it into JSON format. <?php echo json_encode($data); ?> This is the AJAX function being used: ajaxCall("getdata.php", container, function (data) { var co ...

Is there a way to execute a JavaScript function within a loop?

I need to repeatedly call a JavaScript function multiple times. I have attempted to do so in the following way: In Script function changeIt(strgr , idx) { //SomeCode return; } In C# protected void btn_Click(object sender, EventArg ...

Transforming screen recording video chunks from blob into multipart for transmission via Api as a multipart

Seeking guidance in Angular 8 - looking for advice on converting screen recorded video chunks or blogs into a multipart format to send files via API (API only accepts multipart). Thank you in advance! ...

"Explore the versatility of React Day Picker with customizable months and weekdays_long

I have implemented the following packages: "react": "^18.2.0", "react-day-picker": "^8.1.0", and I am attempting to translate the months and days into French. However, despite passing the translated arrays to my < ...

Interact with multidimensional arrays using Vue JS

Is there a way to access properties within objects nested inside multidimensional arrays when using v-for with VueJS? var arr =[{"fruit": {"fruitName": "apple"}, "vegetable":[{"vegetableName": "carrot" }]}]; I am attempting to display it in the following ...

The behavior of TypeScript class inheritance differs from that of its ES6 equivalent

I'm currently developing a custom error handling middleware for my node.js project using express and TypeScript. One key component of this middleware is the AppError class, which extends the built-in Error class. The code for this class is as follows: ...

The useRouter() function doesn't seem to be successfully navigating to the main landing page

"use client" import { useState } from 'react'; import {auth} from '../../firebase-config' import {createUserWithEmailAndPassword} from 'firebase/auth' import { useRouter } from 'next/router'; const SignUp = ...

Display the precise outcome for each division following a successful AJAX callback

Iā€™m facing a challenge in getting individual results for each item after a successful AJAX callback. Currently, I am able to retrieve results, but when there are multiple items, all displayed results are being added to each div instead of just the corres ...

Choose all the HTML content that falls within two specific tags

Similar Question: jquery - How to select all content between two tags Let's say there is a sample HTML code as follows: <div> <span> <a>Link</a> </span> <p id="start">Foo</p> <!-- lots of random HTML ...

Modify request parameters in real-time using JavaScript

i am seeking assistance with a link request: <a href=index.jsp></> also, i have various divs located elsewhere on the page that contain changing values based on user input or specific conditions: <input id="var1" /> <input id="var2" ...

Align the content to the right and center it within the table

One common issue I face is working with tables that contain numbers requiring right alignment to ensure the ones/tens/hundreds/thousands places line up correctly. Here's an example: 2,343 1,000,000 43 43,394 232,111 In these tables, ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

How does the performance contrast between "skip if condition" and "immediately return"?

Do you know if there is a performance variance between these two functions? function x() { var x = false; if(x == true) { ... Numerous lines, like 1 million ... } } function y() { var x = false; if (x != true) { retu ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

What is the best way to execute synchronous calls in React.js?

Currently, I am a novice in working with React JS and I have been tasked with implementing a feature to reset table data in one of our UI projects. Here is the current functionality: There is a save button that saves all overrides (changes made to the or ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

Verify the existence of an array element and proceed to the next one in JavaScript if it does not

I am attempting to select 3 random answers from an array of possible answers and store them in a new array. The new array, selectedAnswers, should contain 3 random answers along with the correctAnswer. While I have made some progress, I am facing an issue ...

Is it possible to utilize both body-parser and Formidable simultaneously?

I've been working on a problem for a few days now, but I'm having trouble understanding certain aspects of it. My website is built using NodeJS and ExpressJS, with form handling done through body-parser. var adName = req.body.adName; var adMess ...

What is the best way to select a color at random from an array without any duplicates?

When iterating through a group of 15 users to create a table row for each user, I am interested in randomly choosing a color from my theme's array of 4 colors for each user. How can I efficiently ensure that no two identical colors are next to each ot ...