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

Streaming live audio through socket io. Need help troubleshooting ALSA shutdown issue

Looking to develop a live audio streaming service using socket.io and ionic 4. On the client side, utilizing cordova-plugin-audioinput and ng-socket-io for Angular. For the server, employing standard npm packages. Node version: 10.16.0 ...

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

Can a Node.js dependent library be integrated into Cordova?

After setting up an android project using Cordova, I came across a javascript library that relies on node.js to function. Since Cordova operates with node.js, can the library be invoked within the Cordova environment? ...

Recreated using CSS and JavaScript: iOS "Background Open" Animation

I am currently seeking a method to replicate the iOS Safari animation that occurs when opening a link in the background (the item jumps up and quickly animates to where it can be accessed) - This same animation is also seen on OSX Safari's "save to re ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

Tips for adding a new column to a website

My goal is to inject some custom HTML and CSS into YouTube in order to create a column on the right side that shifts all content towards the left. Essentially, I am trying to replicate the functionality of the Inspect Tool in Chrome. I am working on a Chr ...

Reasons Why Optional Chaining is Not Utilized in Transpiling a Node.js + TypeScript Application with Babel

Currently, I am delving into Babel in order to gain a deeper understanding of its functionality. To facilitate this process, I have developed a basic API using Node.js and TypeScript. Upon transpiling the code and initiating the server, everything operates ...

JavaScript Bridge function in WebView not invoked

I encountered a strange issue with my application, which functions as an e-reader. To invoke functions for the web view, I utilize a JavaScript class: public class MyJavaScriptInterface { Context mContext; /* Instantiate the interface ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

Tips for incorporating a PDF file into a website when the Adobe Reader add-on is disabled in Internet Explorer

I attempted to insert a PDF into my website using the <embed> tag. Unfortunately, it doesn't seem to be functioning properly in Internet Explorer when the Adobe Reader add-on is disabled. Is there a solution that will allow it to work even if th ...

The issue with the jQuery function lies in its inability to properly retrieve and return values

Within my code, I have a function that looks like this: $.fn.validate.checkValidationName = function(id) { $.post("PHP/submitButtonName.php", {checkValidation: id}, function(data) { if(data.returnValue === true) { name = true; } else { ...

Ending JavaScript promises

I am currently utilizing the Google JS closure library which can be found at https://developers.google.com/closure/library/ Below is the code snippet that I have: if (endDate >= wap.com.ifx.util.IfxComponentUtil.yyyymmdd(currentDate) && goog.o ...

Each div will display the same image twice when loading the image

I have a grid where images are dynamically loaded with a link to a lightbox. Currently, this is how I am achieving it: $(".selection_thumb").each( function(i) { $(this).append("<a data-lightbox='image-1' href='img/folder/folder/"+(++ ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...

From JSON to HTML: the beauty of nesting

I believe there might be a foolish error lurking in my code, waiting to be uncovered. I am working with JSON data sourced from an external site at . The goal here is to extract specific data elements, such as stationShortCode, type, commercialTrack, and s ...

Tips on how to properly display the date in v-Calendar

I'm struggling to format the date output from the v-calendar. Currently, it appears like: Fri Jul 31 2020 00:00:00 GMT+0200 (utc summertime) However, I would like it to display as 2020-07-28. I have searched through the documentation but couldn' ...

Juggling Tasks efficiently with TAP

I have a TAP setup like this: private async void btn_Start_Click(object sender, EventArgs e) { var progress = new Progress<string>(s => textBox1.Text += s); await Task.Factory.StartNew(() => WebHelper.GetPosts(progress,cities[cityidx].l ...

"Troubleshooting issue with jQuery failing to identify PHP variable within an if

I have managed to implement a code that utilizes jQuery and PHP session to add items to the cart. Everything is working smoothly except for displaying the status of the action, such as "Added to cart" or "Updated". The message about the status is stored in ...

The Angular ui-calendar introduces an innovative approach to event addition, providing users with

I need help with adding events to the angular ui calendar. Currently, I am using $scope.events.push() method to add events, but they get reset when changing the month. If anyone has experience with angular ui-calendar and event addition, please provide ...