The function onreadystatechange in AJAX is not being invoked

Currently, I am working on setting up an AJAX request and I am trying to log each change in the console to ensure that it is functioning correctly. Here is the code snippet:

function loadAJAX() {
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = readyStateSwitch(ajaxRequest.readyState);
function readyStateSwitch(x) {
    switch(x) { 
        case 0: ajax0(); break;
        case 1: ajax1(); break;
        case 2: ajax2(); break;
        case 3: ajax3(); break;
        case 4: ajax4(); break;
        default: console.log("no arg"); break;
        }
    }
function ajax0() {
    console.log("0")
    }
function ajax1() {
    console.log("1")
    }
....
ajaxRequest.open("GET", "index.php", true);
ajaxRequest.send();
}

My expectation was to see 0-4 being printed out in the console, but currently only "0" (not initialised) is showing up. Any suggestions for solving this issue?

Answer №1

Make sure to adjust the readyStateSwitch function by properly attaching it as a handler for the onreadystatechange event of the current Ajax request, rather than passing in the current readyState value (which is 0) directly. Update your code to:

function loadAJAX() {
    function readyStateSwitch() {
        console.log(ajaxRequest.readyState);
    }
    var ajaxRequest = new XMLHttpRequest();
    ajaxRequest.onreadystatechange = readyStateSwitch; //passes a reference to the function
    ajaxRequest.open("GET", "index.php", true);
    ajaxRequest.send();
}

Check out the demo here.

Note: The addition of var ensures that you avoid creating accidental global variables and simplifies your code structure.

Answer №2

The reason for this issue is due to the function call.

ajaxRequest.onreadystatechange = readyStateSwitch(ajaxRequest.readyState);

You have forgotten to assign the function properly.

ajaxRequest.onreadystatechange = function() { readyStateSwitch(ajaxRequest.readyState); };

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

Using Twilio Video in server-side Javascript

I am in the process of setting up Twilio Video on my server and have successfully installed the PHP server. The iOS versions of the Twilio video starter app can access this server without any issues. My main query revolves around customizing the Twilio Ja ...

Loading input datalist in Firefox postponed

My goal is to implement an input field for a username that allows users to select from a wide range of names/usernames. I want them to be able to enter a partial string from the name or username. Instead of loading the entire list initially, I aim to load ...

Generate a .py file through an HTML button click and save it to your device

My current project involves developing HTML and JavaScript code for a chatbot. I need to implement a feature where, upon receiving a Python program from the chatbot, a download button should be displayed. When users click on this Download button, they shou ...

Nightwatch is a tool that allows you to interact with elements on a webpage by clicking on an element within

I have a scenario on my website where I have two separate div elements: <div class="wg-block" data-reactid="10" <div class="wg-header" data-reactid="11"/div> .... <h4 class='condition'> "Text" </h4> <div cl ...

What is the most effective way to extract Geolocation API co-ordinates from my nested function and store them in React state?

My goal is to retrieve a user's location once they click a button using the Geolocation API. <button onClick={this.setNewLatLong()}>"Use my location"</button>; I have successfully obtained the latitude and longitude coordinates with the ...

Potentially undefined object that may be nested and destructured

Here is a snippet of my auto-generated query types: export type MatchLivePlayerType = { __typename?: 'MatchLivePlayerType'; playbackData?: Maybe<MatchPlayerLivePlaybackDataType>; }; export type MatchPlayerLivePlaybackDataType = { __t ...

What is the best way to continuously click a JavaScript link until it disappears?

Many websites utilize single-page pagination to display more content with each click. It can be beneficial to view all the content on one page, such as for web crawling purposes. Much like automatically clicking a button using Greasemonkey, how can JavaScr ...

Maximizing Memory Usage in Objects

Which of these coding patterns is considered to be more efficient? Pattern 1: var jso = new Class({ initialize: function () { // implementation }, hiliteField: function () { // implementation } }); Pattern 2: var jso = new Class({ ...

Exporting module files in package.json and supporting multiple type declarations

I'm in the process of creating a TypeScript library and I'd like to use the exports field in the package.json file for exporting. After consulting nodejs and webpack's documentation, it seems that using the exports field is the recommended ...

Validating Input Textbox Content with JQuery Validation Plugin

I am currently utilizing the JQuery Validation plugin found at http://jqueryvalidation.org/ and encountering a specific scenario: Here is an example of the HTML code I am dealing with: <input type="text" name="glass_name" id="glass_name"> &l ...

How can I configure my controller to pass information to a modal window in MVC5 ASP.NET?

In the midst of developing my ASP.NET web application. First, I will outline the process flow of my app: User submits a form Form data is sent to the controller The controller generates a table filled with numbers using tagbuilder, returning it as mvcHt ...

In certain cases, the AngularJS $rootScope may not be properly updating in the resolve function

Strangely, the $rootScope.user variable in my resolve function is not fully assigned with data before the view.html template loads. Most of the time, when I use {{ $root.user.uid }} in my template, I can see the variable data, but occasionally it does not ...

What is causing the search feature to malfunction on the Detail page?

In my project, I have different components for handling shows. The Shows.jsx component is responsible for rendering all the shows, while the ProductDetails component displays information about a single show. Additionally, there is a Search component which ...

What is the process for determining the files array in the nx dep-graph?

With each new release of NX v16.1.4, the file node_modules/.cache/nx/nxdeps.json is created. The structure of this file differs from the one generated by nx graph. In previous versions up to 16.1., the file contained an array named nodes.<app/lib>.d ...

Using Two JavaScript Functions with Identical Names in One HTML File

I am currently facing an issue with a function where the data is retrieved from the getValue() function. The following code snippet is a fragment. grid.js function gridLoadComplete(){ var data = getValue(); } Take into account the following H ...

What is the best way to ensure a string of words in HTML/CSS wraps to the next line seamlessly?

As I work on creating my portfolio website using Bootstrap and custom CSS, I am running into an issue with the game titles breaking in the middle when displayed. Despite my limited proficiency in English, I tried searching for a solution without success. ...

Mysterious AngularJS

I am currently working on minimizing and obfuscating my Angular code, however I have run into a complication. I came across the "Note on minification" page at http://docs.angularjs.org/tutorial/step_05 which has been helpful, but I'm defining my contr ...

Synchronizing two dropdown menus in Angular

I'm having trouble with binding and synchronizing select elements. I am trying to make two select elements work together, but using ng-value="$index" doesn't seem to be doing the trick. These are in sync: <select ng-model="myVar1"><op ...

A Guide on Using Puppeteer to Extract the Value from an Invisible Input Element

import puppeteer from 'puppeteer' async function fetchSteamID(url) { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(url); const element = await page.wait ...

Guide to creating a search bar that scans the text inside an external .txt file

Kindly scroll down to view the updated content, or read through from here for a better understanding of my requirements. I am seeking assistance from an expert in developing a website (not exactly my forte :D) which allows users to search for their banned ...