Retrieving JSON information using JavaScript

I am encountering an issue with the "Ion.RangeSlider" library. I am attempting to dynamically load values via JSON, but I am unable to get the slider to accept the data from the "from" field. It is important that the value is not hardcoded since the user has the ability to modify it.

$(function(){
  'use strict'
  $('#rt').ionRangeSlider({
    min: 100,
    max: 100000,
    step: 10,
    from: loaddata(), -> The data from the function is not being accepted despite console logging.
    postfix: "ms",
    prefix: "Response Time: "
  });
});

function loaddata(){
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var myObj = JSON.parse(this.responseText);
      //document.getElementById("rt").value = myObj.response_time; -> Attempting to change slider value also fails
      console.log(myObj.response_time); -> Successfully logs 2000 in the console
      return myObj.response_time;
    }
  };
  xmlhttp.open("GET", "api/settings.json", true);
  xmlhttp.send();
}

The contents of my json file:

{"response_time":7120,"led":0,"device_ip":"192.168.1.1"}

Answer №1

loaddata() function does not have a return value because AJAX requests are asynchronous. The data from the server is received in the onreadystatechange callback function after the server processes the request and sends a response. It is not possible for the data to be returned directly from the `loaddata()` function as it has already completed execution by the time the callback is triggered.

Trying to return data from the `onreadystatechange` callback will not work as the callback is executed within the `XmlHttpRequest` object, and the returned value remains within that object and cannot be accessed by your code.

To handle this situation, you need to fetch the data first and then use the retrieved data in the `onreadystagechange` callback to initialize the rangeslider. For example:

$(function(){
  'use strict'
  loaddata();
});

function loaddata(){
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var myObj = JSON.parse(this.responseText);
      console.log(myObj.response_time); -> Prints 2000 to the console
      loadRangeSlider(myObj.response_time);
    }
  };
  xmlhttp.open("GET", "api/settings.json", true);
  xmlhttp.send();
}

function loadRangeSlider(from)
{
  $('#rt').ionRangeSlider({
    min: 100,
    max: 100000,
    step: 10,
    from: from,
    postfix: "ms",
    prefix: "Response Time: "
  });
}

For more information, refer to How do I return the response from an asynchronous call?.

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

Display upon hovering, conceal with a button located within a popup container

There seems to be an issue with the code below. Even though it works perfectly in jsfiddle, it breaks in my Chrome and other browsers right after displaying the ".popup" div. Can anyone point out what I might be doing wrong? I found similar code on this si ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

Unable to invoke a function in TypeScript from a Kendo template within the Kendo TreeList component

In my TypeScript file for class A, I am encountering an issue with the Kendo TreeList code. I am trying to call a function from the Kendo template. export class A{ drillDownDataSource: any; constructor() { this.GetStatutoryIncomeGrid ...

Modify the file format depending on the browser being used as Internet Explorer

Currently seeking the most effective method to dynamically alter the file extension of certain images (from .svg to .png) specifically for Internet Explorer users. Uncertain about the optimal approach: consider parsing the HTML code with PHP utilize jQu ...

Why is it that my JQuery sliders appear perfectly fine when viewed locally, but fail to show up when accessed on

I'm facing an issue with two JQuery sliders on my page. The local version works fine, but when I upload it to my web host, only one slider functions correctly. I need both of them to work as intended. Any insights on how to resolve this problem? See ...

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

Sorting of dates in mui-datatables is not accurate

I have dates that are formatted using moment.js, for example ("Sat, Feb 22, 2020 12:55 PM") I retrieve them from firestore, and they appear to come in correctly as I first sort them in descending order. forms.sort(function(left, right) { return moment.u ...

What is the best way to assign user input to my JavaScript variables?

As a newcomer to programming, I am eager to develop an app that utilizes the numerical values inputted by customers as variables for calculations. How can I extract the value from an input using JavaScript? For instance, how can I subtract one input value ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

Configuring Jest unit testing with Quasar-Framework version 0.15

Previously, my Jest tests were functioning properly with Quasar version 0.14. Currently, some simple tests and all snapshot-tests are passing but I am encountering issues with certain tests, resulting in the following errors: console.error node_modules/vu ...

Utilizing Angular's Local Storage Module to efficiently store and manage various elements within an array in Local Storage

I'm facing an issue with storing and retrieving an array from localStorage using the Angular Local Storage Module. Despite following the necessary steps, I am only able to retrieve the last element added to the array. Can anyone provide insights on wh ...

Just arrived in Jersey and encountering a "Unsupported Media Type" error at a resource

I recently moved to Jersey and am new to REST, so please excuse me if my question seems silly. I have a basic resource called Places that should support a GET operation returning points of interest based on the input variable. Below is the input string and ...

Error Encountered During JavaScript Form Validation

Currently, I am troubleshooting a website that was created by another developer. There is a form with JavaScript validation to ensure data is accurately entered into the database. However, I am puzzled as to why I keep receiving these alert messages. Pleas ...

Having trouble sending an array's JSON data to a web service using Angular

I am working with a table where each cell in the rows contains form fields. The table also has two buttons: one button adds a new row to the table, and the other sends all the rows. Below is the code snippet for adding new blank rows: $scope.attributes = ...

What is the proper way to incorporate a ref within a class component?

I am encountering an issue with my class component. I'm wondering if there is a comparable feature to useRef() in class components? Despite several attempts at researching, I have yet to find a solution. ...

What is the best way to target the shadow DOM host element specifically when it is the last child in the selection?

I want to style the shadow DOM host element as the last child. In this particular situation, they are currently all green. I would like them to be all red, with the exception of the final one. class MyCustomElement extends HTMLElement { constructor() ...

Ways to reduce the amount of time spent watching anime when it is not in view

My anime experiences glitches as the black container crosses the red, causing a decrease in duration. Is there a way to fix this glitch? I attempted to delay the changes until the red path is completed, but the glitches persist. delayInAnimeSub = ourVilla ...

The React component fails to re-render upon the initial state update

Currently, I am working on a straightforward survey that requires simple Yes or No answers. The questions are stored in a separate file called QuestionsList.js: Here is the list of questions: const QuestionsList = [ "Do you believe in ghosts?", "Have you ...

I am currently facing an issue in my Node.js environment specifically with the 'oracledb' package

I am encountering an issue with the oracledb modules. Fortunately, I was able to successfully install oracledb. When I run the command like this, -> npm install oracledb njsOracle.cpp njsPool.cpp njsConnection.cpp njsResultSe ...

leveraging socket.io alongside express router

As someone who is relatively new to node.js, I am currently in the process of creating a webchat application. My project consists of a server.js file and a router.js file where I have defined all my routes. Unlike many others, I am not using express-genera ...