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

How about: "Add random HTML content using jQuery each time the page is refreshed

Currently facing this issue: I implemented a jquery plugin fullPage.js by Alvaro Trigo on my website. The plugin script automatically inserts the html structure in certain elements... in my html I have: <div class="section fp-auto-height-responsive" ...

Conceal all div elements except for displaying the initial two

Can an entire div be hidden with only the first 2 entities visible? <div class="inline-edit-col"> <span class="title inline-edit-categories-label">Brands</span> <ul class="cat-checklist product_brand-checklist"> < ...

Having difficulty populating a selection box through an ajax request in Django

I am facing an issue with creating cascading select boxes in my project (backend Django), although I believe most of the backend work has been completed. The JavaScript code I'm using is adapted from a solution found on a stackoverflow post. $(docume ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Decoding JSON with JavaScript following the response from JsonConvert.SerializeObject(json) in a .NET handler

I am currently working on a web application using the .NET platform. I have written a Handler code that returns a JSON object to JavaScript (after making an AJAX request). Here is the Handler code: var wrapper = new { left = left.ToString(), t ...

Transforming an object into an array of objects with the power of JavaScript

Looking to transform an object with the following structure: { From: {"A","B","C"}, To: {"A1","B1","C1"}, value: {1,2,3} } I need to convert this array: [ {from: "A" ,to: "A1" , value: 1 }, {from: "B" ,to: "B1" , value: 2}, {from: "C" ,to: "C1" ...

Toggle the visibility of a section in an external .js file

Is there a way to toggle the display of answers from an external .js file using a button? If I were able to modify the code, I could wrap the answers in a div. However, since it's an external .js file, is this feasible? Here's the fiddle and cod ...

Only enable the last day of each month on the React Material UI date picker, all other dates in the year should be disabled

I've been struggling to find a solution that allows users to only choose the last day of each month in a year, disabling all other days. After searching for answers using the Material UI date picker, I have not been successful. If anyone can guide me ...

The Typescript counterpart to PropTypes.oneOf, utilizing a pre-existing variable

While I know this question has been addressed on Stack Overflow here, I still find myself struggling with a similar issue in my TypeScript project. Currently, I am in the process of converting a JavaScript project to Typescript. Within one of my React com ...

What could be the reason why the navbar ul li a instance is not appearing in Bootstrap 4 modal when using an

Can anyone help me solve the issue I'm having with viewing HTML in a Bootstrap 4 modal? Everything shows up except for the navbar ul li a elements. I've searched for a solution everywhere, but haven't found one yet. Please assist! (I want t ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

Error: Laravel Ajax Request Not Recognized

I am currently working with Laravel and encountering a peculiar issue while using Ajax requests. Strangely, my terminal in VS Code displays the following message (without showing any errors in the console): [Fri May 28 11:03:41 2021] 127.0.0.1:57828 Invali ...

Adjust the color of text, image, and background when the cursor hovers over

Is it possible to change the color of an image on hover by applying a filter like brightness(10)? I tried this, but it whitens all the button, so now I'm not sure how to change the icon color. One way to do it is: <div class="hello"><img ...

Establishing a secondary setTimeout function does not trigger the execution of JQUERY and AJAX

// Custom Cart Code for Database Quantity Update $('.input-text').on('keydown ' , function(){ var tr_parent = $(this).closest("tr"); setTimeout(function () { $(tr_parent).css('opacity', '0.3'); }, 4000); var i ...

Insert a concealed value into a fresh form field following an AJAX call

Within my file named a.html, I have the following code: <input type="button" class="add" /> <div id="middle"></div> Meanwhile, in file b.html, the content is as follows: <form> <input type="submit" /> </form& ...

Uncertainty about the integration of a JavaScript file into a PHP file

Having two PHP files where one is executed through a URL and makes AJAX calls to the second PHP file can present challenges. Sometimes, the AJAX results return HTML content with JavaScript events that do not work as expected. To solve this issue, I have in ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...

Is there a method to incorporate a click event for the confirm button in the ElMessageBox UI element?

When I try to remove data from the table, I need a warning message to appear in the center of the screen first. The delete function is already set up, but I'm struggling to figure out how to implement a confirm button click event with ElMessageBox. I ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

Show an error message in a popup window, following a validation error in Laravel

I am facing an issue with displaying error messages in the update modal form. I am using Laravel request for validation and AJAX to submit the form inside a modal. My goal is to show the error message for each field that is inputted incorrectly. However, i ...