I encountered an undefined type error while converting my code to an Object using JavaScript AJAX

I am puzzled by the TypeError (this.req is undefined) that I am encountering on this line of code: if (this.req.readyState === 4) {

function RequestCORS(url) {
this.url = "http://crossorigin.me/" + url;
this.req = new XMLHttpRequest();
}

RequestCORS.prototype.send = function () {
this.req.open("GET", this.url);
this.req.onreadystatechange = function() {
    if (this.req.readyState === 4) {
        if (this.req.status === 200) {
            console.log(this.req.responseText);
        } else {
            console.log("error request");
            //handleError
        }
    }
};
this.req.send();
};

function main() {
var url = "http://www.01net.com/rss/mediaplayer/replay/";
var requete = new RequestCORS(url);

requete.send();
}


window.addEventListener("load", main);

Your time spent reading is appreciated.

Answer №1

this.req becomes undefined in this scenario due to the asynchronous request causing this to no longer reference the original RequestCORS instance when onreadystatechange is triggered.

To resolve this issue, you can create a local variable within the onreadystatechange function that maintains scope.

var req = this.req;
this.req.onreadystatechange = function() {
  if (req.readyState === 4) {
    if (req.status === 200) {
        console.log(req.responseText);
    } else {
        console.log("error request");
        //handleError
    }
  }
};

Alternatively, you can utilize the bind method.

this.req.onreadystatechange = function() {
  if (this.req.readyState === 4) {
    if (this.req.status === 200) {
        console.log(this.req.responseText);
    } else {
        console.log("error request");
        //handleError
    }
  }
}.bind(this);

Another option is to eliminate the use of this.req altogether.

var req = new XMLHttpRequest();
req.onreadystatechange = function() {
  if (req.readyState === 4) {
    if (req.status === 200) {
        console.log(req.responseText);
    } else {
        console.log("error request");
        //handleError
    }
  }
};

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

Working with MongoDB - Updating multiple subarrays within an array

Is it possible to delete elements from multiple subarrays within a single large array? The structure I'm working with is as follows: { "id": { "$oid": "" }, "users": [ { "friends": [ "751573404103999569" ] }, ...

Combining Socket.io with AJAX for real-time web applications

I am currently working on a web application that relies on Socket.io for delivering notifications to users. I'm wondering if it would be more beneficial to utilize Socket.io exclusively for all client-server communication, or if mixing in traditional ...

Transmit an HTML table to PHP

I have successfully created a dynamic table within a form, but for some reason, it's the only element that is not being fetched. To build this table, I utilized the bootstable framework which allows for easy creation of tables with interactive featur ...

Sorting two different divisions is an example

I need advice on how to toggle between two divs, A and B, without having to reload the page. Ideally, I would like to have three buttons - one that shows only div A when clicked, another that displays only div B, and a third button that shows both A and ...

Updating materials within the Forge

Currently, we have implemented a system where the client retrieves object states when the page loads, changing the colors of 'pending' objects in the model. We continue to poll for changes to update the coloring - initially coloring pending objec ...

Tips on preventing my app from automatically filling a div when the search input is left blank in React

I am currently working on an app that allows users to search for specific Pokemon cards by name. However, I have encountered an issue where the div displaying results is pre-populated with random cards when the user has not entered any input into the searc ...

Querying the api for data using Angular when paginating the table

Currently, I have a table that retrieves data from an API URL, and the data is paginated by default on the server. My goal is to fetch new data when clicking on pages 2, 3, etc., returning the corresponding page's data from the server. I am using an ...

Using Axios to make a GET request with specific parameters to filter and retrieve data within a certain "createdAt" range

I have multiple dates in an Array on my react frontend with the format 'MM/YYYY'. Now I need to fetch history from MongoDB that was created within a specific one-month time range. How do I pass this data in the axios get request? Frontend let da ...

Executing a jQuery AJAX function when the timeout occurs

My goal is to dynamically reload my jQuery DataTables without having to refresh the entire page in order to fetch new data. Here's the initial function I have set up to kick off the process: $(document).ready(function() { $.ajax({ url:&apo ...

Utilizing ajax for fetching a data table

I am new to using ajax and have successfully retrieved data from a table. However, I am now trying to pull in an entire data grid but not sure how to achieve this. In my index.php file, I have the following code: <html> <head><title>Aj ...

Create a single JSON object by searching through two collections in MongoDB

Is it possible for you to assist me in combining data from two collections into one JSON format? Users [ user_id, user_name, city_id ] [ { "name": "Anton", "user_id": 1, "city_id": 1 }, { "name": "Vasiliy", ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

Display header right button based on a condition in React Native using React Navigation

I am looking to conditionally display the Entypo new-message icon in the top right corner of the header based on a boolean variable (if true, then show the icon in the header). Here is a snippet of code where this functionality can be replicated. Thank y ...

The mystery of the unassigned value in $(this).data(value) when using the jQuery click() method

In my Rails 5 application, I am working on creating a dynamic menu that will guide users to different parts of the site based on their location. The idea is that when they click on a specific menu item from the home page, a modal will appear allowing them ...

Comparing Django Templating with AJAX for loading a small div on a web page

My Django server is set up to load a webpage that contains mostly static content, but a few numbers need to be fetched from the database. I am considering the trade-offs between performance and price. One option is to host my Django server on a high-speed ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

Tips for emphasizing the current element without disrupting existing styles

Is there a way to highlight an element with a border without causing it to shift? The script seems a bit glitchy when detecting mouse leaving the area. I'm unable to override parent element properties like border or outline. I also can't use pse ...

Create a base data model that can be duplicated and modified as needed

In my two-player game, both players start with similar data that evolves as the game progresses. I believe I need to create a constructor object that can be duplicated and modified, while also being in JSON format for easy ajax sending. Is there a design ...

Trouble with document updates in MongoDB/Mongoose causing a delay?

I am currently working on updating an object nested in an array in my application. When I test this functionality using Postman, I am experiencing a delay that requires me to make two requests in order to see the updated value. if (taskStatus) { cons ...

Merging audio files using Node Stream

Currently facing an issue with joining 2 .wav files together, as my output file only contains the first item in the array: const writeStream = fs.createWriteStream('server/playback.wav'); const inputFiles = [ `${path.resolve(__dirname, 'r ...