Why is it not possible to isolate the function for xmlHttp.onreadystatechange?

The JavaScript file named test.js is functioning properly when included in my HTML.

function sendData()
{
    var formData = new FormData( document.querySelector("form") );
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "test.php",true); 
    xmlHttp.send(formData); 
    xmlHttp.onreadystatechange =  function(){
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
        alert(xmlHttp.responseText);
    }
}
}

ob = document.getElementById("submit"); 
ob.addEventListener("click",sendData);

Now, I would like to refactor the code and consolidate certain parts into a single function.

        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
        alert(xmlHttp.responseText);

This refactored version is saved as test2.js.

var xmlHttp;
function ready(){        
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
        alert(xmlHttp.responseText);
        }
}

function sendData()
{
    var formData = new FormData( document.querySelector("form") );
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", "test.php",true); 
    xmlHttp.send(formData); 
    xmlHttp.onreadystatechange =  ready;
}

ob = document.getElementById("submit"); 
ob.addEventListener("click",sendData);

However, upon testing, the test2.js script encountered the following error:

test2.js:4 Uncaught TypeError: Cannot read property 'readyState' of undefined
    at XMLHttpRequest.ready (test2.js:4)

There is also a question regarding the proper order of statements for XMLHttpRequest:

    xmlHttp.open("post", "test.php",true); 
    xmlHttp.send(formData); 
    xmlHttp.onreadystatechange =  function(){  }

Some resources suggest an alternative sequence:

    xmlHttp.onreadystatechange =  function(){  }
    xmlHttp.open("post", "test.php",true); 
    xmlHttp.send(formData); 

For further clarification on this matter, refer to this webpage discussing proper ordering of xmlhttp statements.

Answer №1

When coding the function sendData, make sure to avoid using the var keyword as shown below:

var xmlHttp = new XMLHttpRequest();

In order to prevent creating a new local variable with the same name and encountering issues with scope, simply remove the var declaration like this:

xmlHttp = new XMLHttpRequest();

This adjustment ensures that you are working with the global variable xmlHttp instead of declaring a new one locally. While using globals is not recommended practice, it will resolve the issue in this scenario.

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

I would like to include the value of the "file_id" variable in the href attribute of an appended HTML element, but it seems

<div id="invite_popup"> </div> $(".invite_button2").click(function(){ var file_id = $(this).data("id"); //alert(file_id); var popup2 ='< ...

The AJAX file retrieval function is not functioning

I'm working on downloading a file using ajax, but I seem to be facing an issue. Can anyone help me figure out what's going wrong with the code below? url = "https://firebasestorage.googleapis.com/v0/b/analyst-3206a.appspot.com/o/research_reports ...

Using JavaScript to transfer the data ID from a button to a form

I am working on a project where I have a button that triggers a modal: <button type="button" class="btn btn-primary add-subscription" data-toggle="modal" data-workspace_id="{{ workspace.id }}" data-target="# ...

When using React with Firebase, remember to specify the "to" property when using setState to avoid errors

Struggling to figure out what's going wrong after hours of trying. I'm new to React and would really appreciate your help. Initially, my state was an array of accommodations which I mapped over successfully. However, once I connected Firebase wit ...

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...

Strategies for retaining additional fields added via JavaScript when the page is refreshed

var newField = document.createElement("lastExp"); newField.innerHTML = 'insert new form field HTML code here'; document.getElementById("lastExp").appendChild(newField); I have a button that adds an additional form field with a simple click. ...

What is the best way to ensure the alignment of list content and numbering remains separate in HTML while using list-style-position set to inside?

Below is a list with customized styling: ol { background: #ff9999; padding: 20px; list-style-position: inside; } ol li { background: #ffe5e5; padding: 5px; } <ol> <li>Coffee</li> <li>Tea</li> <li>Coca ...

Unresolved CORS Issue in Vue.js Using Axios with undefined Proxy Response

My attempt to retrieve data using a client vueJS on port 8080 from the REST API on port 3000 is resulting in a CORSE Error. Interestingly, a successful POST operation occurs without any issues. To resolve this error, I followed the instructions provided in ...

Conceal when dates align

In my events list, I have dates displayed and would like to hide any end dates that are the same as the start dates. For instance; <span class="start_date">Wed 23rd January</span> <span class="end_date">Wed 23rd January</span> I ...

Autocomplete feature enhanced with the ability to validate and clear out

Here's a snippet of my HTML code: <div class="form-group"> <label for="date_chargement" class="col-sm-4 control-label">Minimum loading date:</label> <div class="col-sm-2"> <input type="text" class="form-control te ...

Material-UI: Avoid onClick event firing when clicking on an element that is overlapped by another in a sticky Table

I have a unique setup in my table where each row, including the header row, begins with a checkbox. This header row has a sticky property. As I scroll through the table, rows start to move behind the header row. If I try to click the checkbox in the heade ...

What is the best method for swapping out an iframe with a div using Javascript?

Having an issue with loading an external HTML page into an iFrame on my website. Currently facing two main problems: The height of the iFrame is fixed, but I need it to adjust based on the content's height. The content inside the iFrame does not inh ...

Generate a sequence of years without relying on the range function

Is there a different approach to generating this array without relying on the range function? Below is an illustration of what I want, but without utilizing the range method. const years = myCustomArrayGeneration(1990, getYear(new Date()) + 1, 1); ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

Once I incorporated Bootstrap into my project, I noticed a noticeable white space between the div elements

Welcome to My Code Playground I was sailing smoothly with my project until I decided to include Bootstrap. Seems like there's something missing in the details, so here I am reaching out. If you spot the issue, please feel free to correct my code. &l ...

AngularJS Material Design sticky header MD table container

I am looking to create a table container to display records with a unique requirement - when the table reaches the top of the screen, its header should stick in place. Can you provide guidance on how to implement this feature? For reference, please check ...

Error: Trying to access 'whenReady' property of undefined variable is not allowed

As a beginner in electron app development, I am facing an issue when running npm start from the terminal. The error message I receive is: TypeError: Cannot read properties of undefined (reading 'whenReady')... This specific problem seems to be ...

Utilizing jQuery and AJAX for submitting multiple POST requests

Experiencing a problem with posting data via AJAX using a drag and drop interface. The data is being sent to the POST URL as intended, but there's a recurring issue where the POST request occurs twice, causing the processing URL to handle the data aga ...

Create an HTML table to view JSON data from a cell on a map

Looking to transform the JSON data into a table by organizing the information based on supplier and product. Below is the JSON input and code snippet: $(document).ready(function () { var json = [{ "Supplier": "Supplier1", "Product": "O ...

The magical form component in React using TypeScript with the powerful react-final-form

My goal is to develop a 3-step form using react-final-form with TypeScript in React.js. I found inspiration from codesandbox, but I am encountering an issue with the const static Page. I am struggling to convert it to TypeScript and honestly, I don't ...