The issue here is that "onreadystatechange" in JS Ajax is not defined, even

For the past day, I've been struggling with this issue and going in circles. Any help would be much appreciated :-)

Synopsis
I'm facing a challenge with asynchronous AJAX calls to CGI using resolver and FQDN variables to obtain DNS resolution results (essentially retrieving the output of `dig @resolver $FQDN`).

Obstacle
While Firebug indicates that GET requests are being fired asynchronously and responses are coming back as expected, I'm having trouble placing these responses into the correct DIVs within the document because the `onreadystatechange` function isn't recognizing the objects.

Additional Info
Even though I'm iterating through an array of objects, it seems they're all being fired instantly even when there's a delay between the iterations.

Below is the code snippet along with my comments:
Since resolver is an array, I've created an array of XMLHttpRequest objects.

function resolve() { 
     var numOfRes = 6;
     var arr = new Array;
     arr[0] = "192.168.1.11";
     arr[1] = "8.8.8.8";
     arr[2] = "8.8.4.4";
     arr[3] = "159.134.0.1";
     arr[4] = "159.134.0.2";
     var len = arr.length;
     var ax  = new Array(); //creating ax as an array 
     for (var i=0; i<=len; i++) {  //iterating through the length of resolvers array
         ax[i] = new XMLHttpRequest(); //assigning to each item in array new object
         //alert(ax[i]); // shows that object exists 
         ax[i].onreadystatechange = function(){ 
              /*=== 
              problem is above - firebug will show:
              **Uncaught TypeError: Cannot read property 'readyState' of undefined**
              **ax.(anonymous function).onreadystatechangehello.cgi:30** 
              oddly it will still populate divs inner html  with 'loading +1 '
              albeit regardless of readystate code (can be 4 or anything else )
              It perplexes me why i is thought as a function? 
              =====*/
              // alert(i);  //if this is enabled I will see readyState==4 populated correctly
              if (ax[i].readyState != 4) {
                   document.getElementById('return_table_'+i).innerHTML="loading "+i;
              }
              if(ax[i].readyState == 4){
                  // get data from the server response
                  var response_ready=ax[i].responseText;
                  document.getElementById('return_table_'+i).innerHTML = response_ready;
              }
         } 
         ax[i].open("GET","av.pl?resolver=" + arr[i] +"&fqdn=google.com",true); //works 
         ax[i].send(null); //works 
      }

 }

Answer №1

It is a common issue that occurs when working with variables in JavaScript. Variables are scoped at the function level, not at the block statement level. This means that as you loop through a variable like "i", each function created within the loop will share the same "i". So, when these functions are executed, the value of "i" will be what it was at the end of the loop - often beyond the array's length.

To avoid this problem, you should create these functions inside another function. One way to do this is by having a separate local function:

 function makeReadyStateHandler(i) {
     return function() {
          if (ax[i].readyState != 4) {
               document.getElementById('return_table_'+i).innerHTML="loading "+i;
          }
          if(ax[i].readyState == 4){
              // get data from the server response
              var response_ready=ax[i].responseText;
              document.getElementById('return_table_'+i).innerHTML = response_ready;
          }
     };
 }

You can then call this function within the loop like so:

      ax[i].onreadystatechange = makeReadyStateHandler(i);

By using a separate function in this manner, you ensure that each handler function will have its own independent copy of "i," frozen at the correct point in the loop. The function will generate a new function as its output, which you can use as the event handler.

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

"Employing AJAX along with jQuery in .NET often leads to the error message stating, 'The requested resource was not

Could use some guidance on setting up a simple Ajax call in .NET Any suggestions? [WebMethod] public string Greetings() { return "Hello World"; } When I try to access the webmethod through my browser using this URL: I encounter the error: "The r ...

Creating a CSS circle spinner with a half moon shape is an innovative way to add a unique touch

Image: Circular spinner rotating along the border rim of other solid circle For more details, please visit: https://codepen.io/sadashivjp/pen/oqqzwg I have created a UI codepen here and welcome any modifications or solutions. The code snippet is provided ...

Code error detected on basic webpage

I've been experimenting with my local storage and have encountered a strange issue. The code example that I had previously tested successfully is now not working, and I can't figure out what went wrong. Check out this link for additional informa ...

Utilize the clearChart() function within Google charts in conjunction with vue-google-charts

I have integrated vue-google-charts to display various charts on my website. I want to allow users to compare different data sets, by enabling them to add or delete data from the chart. In order to achieve this functionality, I need to find a way to clear ...

Leverage the NextRouter functionality without the need for a React component

I've created a custom hook that checks if a user is logged in and redirects them to the login page if not. Below is a simplified version of the hook assuming the user is not logged in: import { useRouter } from 'next/router'; export default ...

Obtain the jQuery dialog's closure event within the $.Ajax completion function

I have developed a custom jQuery plugin that utilizes jQuery Dialog to showcase messages. Specifically, I am using it within my jQuery $.ajax -->done function. My goal is to capture the close event of the Dialog in the .ajax function so that I can redire ...

How to address critical vulnerabilities found in a Vue.js project that relies on the 'vue-svg-loader' dependency, specifically impacting 'nth-check', 'css-select', and 'svgo'?

Attempting to launch a Vue version 2 project, encountered the following error: # npm audit report nth-check <2.0.1 Severity: high Inefficient Regular Expression Complexity in nth-check - https://github.com/advisories/GHSA-rp65-9cf3-cjxr fix available ...

Unable to relocate the cursor to an empty paragraph tag

Wow, I can't believe how challenging this issue is. My current project involves implementing the functionality for an enter key in a content editable div. Whenever the user hits enter, I either create a new p tag and add it to the document or split t ...

Parameterized Azure Cosmos DB Stored Procedure

I am currently learning about Azure Cosmos Db, and I am in the process of developing a simple JavaScript stored procedure that will return a document if a specific Id is provided. However, when I run the stored procedure, I do not receive a "no docs foun ...

How to use JQuery UI sortable to automatically scroll to the bottom of the page

Having trouble with a few sortable tables and here is how I initialized the sortable object: var options = { helper: customHelper, handle: ".moveTargetDeliverables", containment: "#fieldset_deliverables_summary", tolerance: 'pointer&a ...

Leveraging jest.unmock for testing the functionality of a Promise

I've implemented Auth0 for managing authentication in my React App. Below is the code snippet I am trying to test: login(username: string, password: string) { return new Promise((resolve, reject) => { this.auth0.client.login({ ...

What is the best way to implement loading a script after an AJAX request has

var currentTallest = 0, currentRowStart = 0, rowDivs = new Array(), $el, topPosition = 0; $('.blocks').each(function() { $el = $(this); topPosition = $el.position().top; if (currentRowStart != topPosition) { // we just came to a new row. ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

What is the best way to pass only the second parameter to a function in TypeScript?

Let's consider a TypeScript function as shown below: openMultipleAddFormModal(commission?: Commission, people?: People): void { // some data } To make a parameter optional, I have added the Optional Chaining operator. Now, how can I modify the code ...

There seems to be an issue with Ajax functionality within the WordPress admin

As a beginner level WordPress developer, I am currently halfway through creating a newsletter plugin administration panel. Unfortunately, the jQuery.post ajax I am using for form submission in this admin panel is not working. Strangely enough, the same Wor ...

Organizing outcome searches through ajax

I have a result table displayed on the left side https://i.stack.imgur.com/otaV4.png https://i.stack.imgur.com/pp9m0.png My goal is to transform it into the format shown on the right side of the table In a previous inquiry found here, @Clayton provided ...

Send form without reloading the page (partially updating the page)

Code snippet in index.php HTML head: <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script> <script> // Ensurin ...

Navigate through a series of div elements using Jquery

I need help figuring out how to make the window scroll between different divs in a sequence. The issue is that my current code only works for one specific div at a time. $('.down_arrow').click(function(e){ $('html, body') ...

Can one utilize HTML's .querySelector() method to target elements by xlink attribute within an SVG document?

Here is the scenario: <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <a xlink:href="url"></a> </svg> </body> Now, can you utilize the HTML DOM's .querySe ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...