Having difficulty sending variables to onreadystatechange

Here is the latest version of the source code:

var xhttp = new XMLHttpRequest();
  
function passVars(var1, var2, var3) {
  if (var1.readyState == 4) {
    if (var1.status == 200) {
      var data = var1.responseText;

      if (data) {
        playSuccess();
        classSwitch(data, var2, var3);
      } else {
        playFailure();
        alert("Error: returned status code " + var1.status + " " + var1.statusText);
      }
    }
  }
}
  
xhttp.onreadystatechange = function() { 
  passVars(xhttp, "tab", "p1234");
};

xhttp.open("POST", "index.php", true);
xhttp.send(formData); //formdata is a POST send to PHP's backend which returns responseText = 0 or 1 for var data

function classSwitch(state, sOrigin, stateButtonID) {
  if (sOrigin === "tab") {
    Monitored = state;
    if (state === "1") {
      if (document.getElementById("setmonitoring").classList.contains("productmonitoringdisabled")) {
        document.getElementById("setmonitoring").classList.remove("productmonitoringdisabled");
      }
      document.getElementById("setmonitoring").classList.add("productmonitoringenabled");
    }
    
    if (state === "0")  {
      if (document.getElementById("setmonitoring").classList.contains("productmonitoringenabled")) {
        document.getElementById("setmonitoring").classList.remove("productmonitoringenabled");
      }
      document.getElementById("setmonitoring").classList.add("productmonitoringdisabled");
    }
  }
  
  if (sOrigin === "issues") {
    if (state === "1") {
      if (document.getElementById(stateButtonID).classList.contains("productmonitoringdisabled")) {
        document.getElementById(stateButtonID).classList.remove("productmonitoringdisabled");
      } else document.getElementById(stateButtonID).classList.add("productmonitoringenabled");
    }
    
    if (state === "0")  {
      if (document.getElementById(stateButtonID).classList.contains("productmonitoringenabled")) {
        document.getElementById(stateButtonID).classList.remove("productmonitoringenabled");
      } else document.getElementById(stateButtonID).classList.add("productmonitoringdisabled");
    }
  }
}

I have tried numerous methods to pass them using primarily answers from Stack Overflow and each time var2 and var3 are undefined. This code is being used in an early alpha version of an inventory control system. The goal is to pass the element's id to change the button class when the backend returns the product's current monitoring state.

Any suggestions on how to successfully pass those variables? Thank you in advance.

Answer №1

Your current code implementation needs to be improved. Passing xhttp in an asynchronous call is not recommended. Here's a revised version of your code snippet for better execution...

xhttp.onreadystatechange = function() { 

  if (xhttp.readyState == 4) {

    if (xhttp.status == 200) {

      var data = xhttp.responseText;

      if (data) {

        playSuccess();

        classSwitch(data, 'tab', '1234');

      } else {

        playFailure();

        alert("Error: returned status code " + xhttp.status + " " + xhttp.statusText);
      }
    }
  }

};

Answer №2

Here's a simple example demonstrating how to effectively pass parameters to the onreadystatechange callback function. The code provided contains unnecessary complexities as there is no requirement to pass the xhttp variable to the callback since it is already accessible within the scope.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://developer.mozilla.org/");
xhr.send();
xhr.onreadystatechange = function() {
  callback("info", "5678");
};

function callback(param1, param2) {
  console.log(`param1 = ${param1}`);
  console.log(`param2 = ${param2}`);

  //Perform necessary checks on xhr.readyState and xhr.status within this function
  console.log(`xhr.readyState = ${xhr.readyState}`);
  console.log(`xhr.status = ${xhr.status}`);
}

Answer №3

utilized

function retrieveData(data1, data2, data3) {
xhr.onreadystatechange = function(response) {}
}

The "response" in the function bracket will reference all variables previously defined in the retrieveData function.

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

Avoid refreshing the page when adding an item to the cart

I am in the process of creating a online shopping cart and I'm looking for ways to avoid the page from reloading when adding a product to the cart. At the moment, my approach involves using the GET method to add products to the cart. <a href="car ...

Displaying a PHP variable on the console through the power of jQuery and AJAX

I'm attempting to display the value of a PHP variable in the browser's console using jQuery and AJAX. I believe that the $.ajax function is the key to achieving this. However, I am unsure about what to assign to the data parameter and what should ...

Attributes required are not functional on mobile devices

Good day! I have encountered an issue with the required attribute on a form on my website. It seems to be working perfectly on my browser, but not on mobile devices. Has anyone else experienced difficulties with jQuery, JavaScript, or Node packages? <f ...

Ways to refresh a canvas element without requiring a full page reload

My goal is to restart a canvas on a website without reloading the page, making the restart dynamic. However, I've noticed that after multiple restarts, the animation slows down and memory usage increases. The situation is complicated by my use of Met ...

To complete Mocha tests, ensure to use the done() method. However, keep in mind that the resolution method is too specific. Choose either to specify a callback *or* return a Promise, but not both simultaneously

Encountering a frustrating issue with a mocha test. When I leave it alone, it freezes and displays: Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. If I include `Pro ...

Utilizing Three.js with interactive functionalities and advanced transformation controls

I'm facing an issue with my project where I am using three.interaction to capture click events on certain objects and add transformControls to them. The problem I'm encountering is that the transform controls seem to block the click event on oth ...

Can someone clarify the meaning of (e) in Javascript/jQuery code?

Recently, I've been delving into the world of JavaScript and jQuery to master the art of creating functions. I've noticed that many functions include an (e) in brackets. Allow me to demonstrate with an example: $(this).click(function(e) { // ...

Ways to update list item text with jQuery

I am attempting to create a button that can replace the content of a list item. Although I have looked at other solutions, I keep encountering this error message: Uncaught TypeError: Object li#element2 has no method 'replaceWith' I have experime ...

Utilizing function arguments in ReactJS

Currently, I am in the process of learning ReactJs and have an inquiry about the code snippet below. Would someone be able to clarify the functionality of the removeTour code and why the id parameter is being used within the function? const removeTour = (i ...

Utilize the JSON response upon successful completion of an AJAX request

I'm currently working with this code snippet: function openIzmeni(value) { $.ajax({ url: "getRzaizmenu.php", type: "POST", async: true, data: { vrednostid:value}, //your form data to post goes here as ...

angular $stateProvider behaving unexpectedly with routing

Within my main file titled index.html, I have incorporated the following basic markup... <body ng-app="starter" ng-controller="AppCtrl"> <div ui-view></div> </body> In my separate file called app.js, I am utilizing $stateProvi ...

What is preventing me from installing react-router-transition on the 1.4.0 version?

$ npm install -S <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dffe8eceef9a0ffe2f8f9e8ffa0f9ffece3fee4f9e4e2e3cdbca3b9a3bd">[email protected]</a> npm ERROR! code ERESOLVE npm ERROR! Unable to r ...

What is the best way to transfer information from a model to the screen?

I need assistance with adding a Todo using a model. When I click the Add todo button located at the bottom of the page, it opens the model. I want to be able to add whatever I type in the input field to the list. How can I send the input field data to the ...

Determining the total number of current connections using JavaScript, jQuery, and Selenium WebDriver

I need your assistance as I've encountered a roadblock. In my automated tests using Selenium WebDriver + Java, I rely on the following code snippet to check for active background AJAX connections: private boolean hasNoActiveConnections() { retur ...

Executing a Javascript function repeatedly

Here is a sample JavaScript function: function f1() { alert("HI"); } I have two different locations where I am calling the same JavaScript function: <input type="submit" id="btn1" onclick="f1()"/> <input type="submit" id="btn2" onclick="f1 ...

Using $.ajax to call a Perl script that retrieves data using fetchall_arrayref and displays it

I have encountered an issue with my $.ajax call to a Perl file that retrieves data from MySQL using fetchall_arrayref. The problem I am facing is getting this data back into ajax and displaying it as dropdown options in a <select> element using jQuer ...

What is the best way to retrieve the image name and image type when uploading them through the Froala editor

After uploading an image using Froala Editor, I encountered a problem where I couldn't retrieve the image name and type in ajax. I needed to find a way to transfer that file to my own server with Laravel. Here is the code snippet for the ajax part: ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

Is it possible to update both package-lock.json and package.lock simultaneously?

Before releasing to NPM, I always make sure to update the minor version. My usual process includes: - Modifying the package.json - Executing npm i to synchronize package-lock.json with the changes. This prepares both files for publishing. Is there a simpl ...