The Ajax readyState consistently displaying a value of 0

I am encountering an issue with my Ajax code as it always returns 0 when I access 'readyState'. I have not been able to identify the source of the problem yet. Any assistance on this matter would be greatly appreciated:

var xhr = null;
function performAjax(inputUrl){

    // initialize the XMLHttpRequest object
    try{
        xhr = new XMLHttpRequest();
        alert("XMLHttpRequest");
    }
    catch(e){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // handle compatibility for older browsers
    if( xhr == null ) {
        alert("Your browser does not support Ajax");
        return;
    }

    // retrieve the URL
    var url = inputUrl;
    alert(inputUrl);
    // obtain the Ajax response
    xhr.onreadystatechange = handler();
    //alert(xhr.readyState);
    xhr.open("POST", url, true);
    xhr.send(null);
}

function handler() {

    alert("Handler: " + xhr.readyState + " Status: " + xhr.status);
    // only process loaded requests
    if(xhr.readyState == 4) {   // state 4 indicates data has been received
        alert("here");
        if(xhr.status == 200) { 
            alert(xhr.reponseText);
        }
        else alert("An error occurred with Ajax");
    }
}

Answer №1

Make sure to correctly assign the handler function:

xhr.onreadystatechange = handler; // <--- MAKE SURE TO OMIT PARENTHESES

By including parentheses, you are requesting for the function to be executed. Without them, you are simply referencing the function, which is the desired behavior.

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

Synchronized multiple file uploads using AjaxFileupload

Currently, I am working on implementing a feature to upload multiple files asynchronously. One of the functionalities I want to include is a SMTP client where users can select files, compose a message, and then send an email. I have tried using ajaxfileu ...

In search of an improved scoring system for matching text with JavaScript

For many of my projects, I've relied on String Score to assist with sorting various lists such as names and countries. Currently, I am tackling a project where I need to match a term within a larger body of text, like an entire paragraph. Consider t ...

Protractor - Resolving as pending promise when executed

I have been working on creating a function that can search through an array of elements and return the first element that meets certain criteria. Here is my test code that works as expected: element.all(by.css('_cssSelector_')).filter(function( ...

Implementing a search filter in Vue.js using a nested for loop

I am currently working with a JSON object that contains nested objects and I need to iterate over them to extract data. Everything is functioning correctly, but now I want to implement a search/filter feature where the search is performed on the second lev ...

Guidelines on concealing the parent component while the child component is loading in Angular 2

In my latest project, the view setup is as follows: Upon page load, the Parent Item Description should be visible while the Selected sub item description remains hidden. When a Sub Item x is selected, the Parent Item Description should disappear and only ...

Loop within a promise results in undefined

Within my application, there is a function that returns a promise. Inside this function, I wait for an image in the DOM to become available and then extract that element to generate base64 data from it. getCodesOfOneMerchant(merchantDataEntry: MerchantData ...

Create an interactive mechanism where one scrollbar dynamically adjusts another scrollbar and vice versa

Using the provided js-bin, how can I synchronize scrolling between the "left" div and the "right" div when using the mouse wheel? Currently, if you uncomment the code block, the scrolling behavior changes from scrolling by 100px per scroll to scrolling pi ...

The values returned by the Node.js API can vary for identical requests

I am currently learning how to use Node.js + Express in order to create a REST API. Within this API, I have implemented the following method: apiRouter.route('/training/session/byId/:id_session') // ===== GET ======= .get(function(req, res ...

Is there a benefit to using middlewares instead of the standard built-in functions in Express.js?

Express.js offers a wide range of middlewares that replace built-in functions. One example is body-parser, which parses HTTP request bodies, replacing the built-in function express.bodyParser. body-parser replaces the built-in function express.bodyParse ...

Change the function from onLoad to onClick exclusively

I'm experiencing a particle explosion on my webpage due to this code. I connected the onClick function to a button in my HTML so it executes only when that specific button is clicked. However, the function automatically runs when I load the HTML and ...

Stop the background from being visible using the jQuery Cycle plugin

I'm facing a challenge with the cycle plugin for jquery when creating a slideshow. The transition between slides allows what's underneath to show, but I want a smoother transition where one slide truly fades into the other without the background ...

Issue with Webpack - npm run start and build operation not functioning?

Although I typically use create-react-app for my React projects, I decided to create one without it. However, I am encountering issues with the webpack configuration as I am not very familiar with it: This is how my package.json file looks like: { " ...

Automatically refresh and update HTML content

I've created a temp.php file that generates output in JSON format: [{"Date":"2016-10-25 16:12:30","Temp":"1.00"},{"Date":"2016-10-25 16:24:05","Temp":"1.00"},{"Date":"2017-02-25 23:04:04","Temp":"1.00"},{"Date":"2017-02-25 23:05:34","Temp":"1.00"},{" ...

Combining Nested Objects in MongoDB

I have searched extensively for a solution but I am struggling to find a resolution to my issue. I have two MongoDB (Node.JS) collections: user & statistics. My goal is to merge the results using aggregate. Below are the structures of the collection ...

Is it better to use regexp.test or string.replace first in my code?

When looking to replace certain parts of a string, is it better to use the replace method directly or first check if there is a match and then perform the replacement? var r1 = /"\+((:?[\w\.]+)(:?(:?\()(:?.*?)(:?\))|$){0,1})\ ...

Problem Installing Express Sharp using Docker

When deploying via Docker, I encountered an error with sharp, even though it works fine on my workspace. I followed all the steps but still faced issues. Error: 'linux-x64' binaries cannot be used on the 'linuxmusl-x64' platform. P ...

Obtain $stateParams excluding UI-navigation

Is there a way to access $stateParams without using a <ui-view> tag in the HTML? I'm trying to make this code function properly: .config([ '$locationProvider', '$stateProvider', function($locationProvider, $stateProvide ...

I'm curious about what exactly happens when the NextJS Link component is triggered and how we can effectively capture and respond

As I was developing a simple navbar that uses a JSON data to dynamically generate its links, I encountered the need to visually persist the active link/route. To achieve this, I experimented with two different implementations: Initial approach: In the Me ...

Struggling to retrieve information from a JSON file and display it within a component?

After accessing the JSON data and storing the necessary values in a dictionary named details, I am encountering an issue where the values are displayed when console logged from inside the function but appear as undefined when console logged in the parent f ...

Is it possible to refresh the page without using a hashtag and stay on the same page in AngularJS

Is it possible to refresh my view from the navigation bar without displaying the server folder? I have the html5Mode activated: if(window.history && window.history.pushState) { $locationProvider.html5Mode(true); } ...