Having trouble fetching results from AJAX objects using vanilla JavaScript?

I am currently working on developing my own AJAX prototype without relying on jQuery or any other libraries. However, I am facing an issue where I cannot retrieve any results and the breakpoint set on a specific line is not triggering:

The problem seems to lie in the following part of the code:

Why is it showing as undefined, even though I have initialized the HttpXml instance using the init() function previously:

I am attempting to send a request from another part of the program by doing the following:

var ajaxInstance = new GC3D.Ajax();
ajaxInstance.init();
var response = ajaxInstance.sendRequest({
    HttpMethod: 'GET',
    UrlEndpoint: '/SomeService?function=someFunctionName'
});

This is the complete source code for the prototype:

GC3D.Ajax = function() {
    this.httpRequest = undefined;
    this.listExceptions = undefined;
};
GC3D.Ajax.prototype.init = function() {
    this.listExceptions = [];

    if ( window.XMLHttpRequest ) this.httpRequest = new XMLHttpRequest();
    else if ( window.ActiveXObject ) {
        try {
            this.httpRequest = new ActiveXObject( 'Microsoft.XMLHTTP' );
        }
        catch ( exception ) {
            this.listExceptions.push( exception );

            try {
                this.httpRequest = new ActiveXObject( 'Msxml2.XMLHTTP' );
            } 
            catch ( exception ) {
                this.listExceptions.push( exception );

                try {
                    this.httpRequest = new ActiveXObject( 'Microsoft.XMLHTTP' );
                } 
                catch ( exception ) {
                    this.listExceptions.push( exception );
                }
            }
        }
    }

    if ( !this.httpRequest ) {
        console.error( 'Can\'t create a HTTP Request instance for AJAX! Possible problems:' );
        console.error( this.listExceptions );
    }
    else this.httpRequest.onreadystatechange = this.getContentFromRequest;
};
GC3D.Ajax.prototype.sendRequest = function( properties ) {
    if ( this.httpRequest !== undefined ) {
        this.httpRequest.open( properties.HttpMethod, properties.UrlEndpoint );
        this.httpRequest.send();
    }
    else throw 'HTTP Request instance isn\'t defined!';
};
GC3D.Ajax.prototype.getContentFromRequest = function() {
    if ( this.httpRequest !== undefined ) {
        if ( this.httpRequest.readyState === 4) {
            if ( this.httpRequest.status === 200 ) return this.httpRequest.responseText;
            else console.log( 'There was a problem with the request in GC3D.Ajax.' );
        }
    }
};
GC3D.Ajax.prototype.get = function() {
    return this.httpRequest;
};

Could you please point out what might be incorrect in the code causing it not to trigger at the line mentioned above?

Thank you

Answer №1

The issue arose due to the context of this being lost in this situation:

else this.httpRequest.onreadystatechange = this.getContentFromRequest;

Upon assigning the function above to the event, the instance of this was lost.

Consider a scenario where the exact function name is unknown and it is an anonymous function:

this.someEvent.onSomething = function( item ) { ... };

In this case, the anonymous function loses access because of the definition of scopes with {}, limiting the visibility of this.

A similar problem occurred in my code when I modified a section to:

GC3D.Ajax.prototype.getContentFromRequest = function() {
    if ( this.readyState === 4 ) {
        if ( this.status === 200 ) return this.responseText;
        else console.log( 'There was a problem with the request in GC3D.Ajax.' );
    }
};

After making this adjustment, the code now functions correctly!

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

Having trouble uploading several files with Multer functionality?

I've encountered an issue with Multer in Node.js where I can't seem to select and upload multiple files. In a previous exercise, I had no trouble uploading a single file, but now I'm struggling with enabling multiple uploads. What am I mis ...

What could be the reason for the page scrolling upwards when clicking on href="#"?

I am encountering an issue with a hyperlink <a href="#" id="someID">Link</a> that is located further down the page. This link is used to trigger an Ajax request, but whenever it is clicked, the page automatically scrolls back to the top. I have ...

The npm package installation process encountered difficulties in accessing the Chart.Js library

Currently, I am in the process of developing a web application that tracks and logs hours spent on various skills or activities. The data is then presented to the user through a bar graph created using Chart.js. Initially, I was able to display a mock grap ...

Simulating a PubSub publish functionality

I have been trying to follow the instructions provided in this guide on mocking new Function() with Jest to mock PubSub, but unfortunately I am facing some issues. jest.mock('@google-cloud/pubsub', () => jest.fn()) ... const topic = jest.fn( ...

Creating a personalized and versatile table component with unique functionality: where to begin?

Looking to create a versatile table component that can adapt for both desktop and mobile versions. If the screen width is below 720px, it should display a table using div, ul, li elements with a "load more" button at the bottom. If the screen width i ...

svg-to-json.js | The mysterious disappearing act of my file

After completing the installation process for svg-to-json.js as detailed in my previous post, I ran the command: node svg-to-json.js filename.txt The expectation was that a .json file would be generated, but I couldn't locate it. Is it supposed to ...

When a button is clicked within a partial view, it will redirect to the parent action

I am struggling with implementing an AJAX call using jQuery in a partial view within my application. I have a parent view called 'Parent' where I am using @Html.BeginForm and a submit button to save data. However, whenever I try to make the AJAX ...

What could be the reason my script fails to execute during an AJAX refresh?

As I was working on my project's avatar uploader, everything seemed to be going smoothly until this morning when chaos ensued. It was a moment of pure sadness. Initially, selecting a file would prompt the crop tool to appear immediately, and it worke ...

Simple JavaScript validation for inputting names

Hey there, I'm a beginner in javascript and I am struggling with a simple input validation using else if statements. Every time I run the code, it goes directly to the else condition. Can someone please assist me? <!DOCTYPE html> <html lang=& ...

Having trouble with Material UI ListItem and setting a custom key prop

While using Material UI for React, I encountered an issue when attempting to pass a key prop to a ListItem: A warning popped up stating that key is not a valid prop. Trying to access it results in undefined. If the same value is needed within the child ...

What is the best way to retain AJAX data even when navigating back without losing it?

After receiving an Ajax response, I display a set of data on my home page. When I click on any of the data, it takes me to another page. However, when I click the back button on the browser, it just navigates me back to the homepage without showing the A ...

How can Array.map() be combined with D3 selection?

Is there a way to calculate the maximum length of text elements in an SVG selection similar to using Array.map()? Currently, I am retrieving the maximum length of a selection of SVG <text/> elements by utilizing .selectAll(...)[0].map(...), but it fe ...

Using `babel/register` does not seem to be functioning as expected

I am working on an isomorphic app built in ES6 on the client side using the Babel transpiler. I would like my express server to also utilize the same ES6 syntax as the client code. Unfortunately, attempting to use require('babel/register') has n ...

I am experiencing an issue where the jquery sleep function is not being executed during

I currently have an Ajax request that is awaiting a response from another process. function checkProcess() { var flag = 0; while (flag === 0) { $.ajax({ url: "cs/CheckForProcess", async: false, success: ...

Achieving success in element-ui vuejs involves validating the state with the :error parameter

I recently developed an app using Laravel, Vuejs, and Element-ui. Within my form, I have utilized the "error" property to indicate that Laravel validation is in place. <el-form-item label="First Name" prop="firstname" :error="registerForm.errors.get(&a ...

When an image is clicked, I am attempting to access data from a Sharepoint list

In my Sharepoint list, there are three columns: Image, Title, and Description. I am using ajax to retrieve the items from the list. The images can be successfully retrieved, but my goal is to display the title and description of the clicked image when an ...

Exploring the dynamics of Django, Webpack, and Vue with the added feature of code splitting: A guide to customizing chunk

I am currently using Django in conjunction with Webpack and Vue, as well as implementing Code splitting within Webpack. The issue I am facing is that Webpack splits chunk files from the source code of .vue files, but I am unable to load these chunk files i ...

Troubleshooting why jQuery Ajax post is not sending parameters

Struggling with jQuery's $.ajax() function to send form data to an MVC route. Despite passing data, all parameters end up null in the MVC action: jQuery: $(function () { $('#signupform').submit(function (e) { e.preventDefault() ...

React Native - Listview triggering multiple refreshes when pulled down

As I attempt to implement the onScroll function for ListView to detect when a user has pulled the list down beyond a certain pixel value in order to trigger an AJAX call and refresh the list, I am facing an issue where it fires multiple times leading to a ...

Navigating through content on a screen can be accomplished in two

Is it feasible to incorporate both horizontal and vertical scrolling on a website using anchor tags? I recently created a website with horizontal scrolling for each main page. Within some of these main pages, there are subsections that I would like to hav ...