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

Requesting CORs on Web API version 2.0

After enabling CORs on a Web API, I encountered an issue where GET and POST requests were failing on Chrome. Interestingly, the GET request worked fine on MS Edge, but the POST request threw two error messages in the console: The request could not be proc ...

Executing an Ajax request to a document containing <script> elements

Recently, I developed a sample page that effectively mimics table layout pages but without relying on the traditional mobile-unfriendly table features. The structure of the page is as follows: <html> ... <body> <div type="page" ...

Transforming JSON data into a visually appealing pie chart using highcharts

I'm having trouble loading my JSON string output into a highcharts pie chart category. The chart is not displaying properly. Here is the JSON string I am working with: var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\ ...

Modifying data in JSON object using Python

Struggling with updating a value within a JSON object. Here's the code snippet: import json userBoard = '' #example below, loaded separately @app.get("/setItem") def setItem(): id = request.args.get('itemId') id = int(id[2 ...

Concealing HTML content with a modal overlay

There are security concerns with my authentication overlay modal, especially for users familiar with CSS and HTML. Is there a way to hide the HTML behind the modal so it doesn't appear in the page source? The code below is just an example of a modal ...

Using EJS to Render a Function Expression?

Has anyone been able to successfully render a function call in express using EJS? Here's what I've tried so far: res.render("page", { test: test() }); Can someone confirm if this is possible, or provide guidance on how to call a function fr ...

Could you clarify the significance of the brackets in this TypeScript Lambda Expression?

I'm currently delving into an Angular book, but I'm struggling to locate any definitive documentation regarding the usage of square brackets in a lambda expression like [hours, rate]) => this.total = hours * rate. While I grasp that these para ...

Creating a JSON object from text using JavaScript is a straightforward process

Looking to generate an object using the provided variable string. var text ='{"Origin":"Hybris","country":"Germany","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

"Threads snap as soon as they begin to be put to use

Encountering an issue with the command yarn run serve, the error log states: $ vue-cli-service serve INFO Starting development server... 10% building 2/2 modules 0 activeevents.js:173 throw er; // Unhandled 'err ...

How can I streamline a kendo UI MVC project by eliminating unnecessary components?

After switching my MVC 5 project to utilize Kendo UI, I've noticed a significant increase in the number of files being used. Since there is no need for supporting other cultures at the moment, can I confidently delete the files within the messages an ...

Is it true that document.execCommand only works with buttons and not links?

Below is the code snippet I am working with: <div contenteditable="true" style="height:100px;width:100px;border:1px solid; " class="editor"></div> <a class='bold' style="height:10px;width:10px;">B</a> $(function(){ ...

Leveraging Webpack and Jest for seamless module importing in a development project

I've been working on a Node project and utilizing imports and exports extensively. To package the frontend code, I opted for Webpack. However, it seems to require running as common JS. Moreover, Jest is being used in my project, which led me to spec ...

The counterpart of the RxJS setTimeout operator

Looking for a RxJS operator alternative to set/clearTimeout in these circumstances: this.mouseEnterSubscription = this.mouseEnterStream .subscribe(() => { this.timeout = setTimeout(() => { void this.playVideo(); }, 500) }); this.mo ...

Issue: Angular is indicating that the 'feedbackFormDirective' member is implicitly assigned with type 'any'

I am encountering an error in my project while using Angular version 12. Despite extensive research, I have been unable to find a solution. Here is my .ts file: import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Feedba ...

A comprehensive guide on harnessing the power of server-sent events in express.js

After incorporating the express.js framework, I configured my REST server. Now, I am interested in integrating server-sent events (sse) into this server. However, upon implementing the sse package from npmjs.com, an error occurs. It seems that the error is ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

Make sure to incorporate certain node_modules folders within Babel 7

My issue involves a dependency located in the node_modules directory that requires compilation through Babel. Despite upgrading my stack, I am unable to get Babel to compile the dependency. Current versions: @babel/core 7.5.4 webpack 2.7.0 Here is my w ...

Error message in Angular about undefined JavaScript function

Struggling to make my Angular 17 project functional with Bootstrap (5) and the datePicker feature. Despite following tutorials, I keep encountering a "ReferenceError: datePicker is not defined" error during the app build process. Here are the steps I&apos ...

Merge nested arrays while eliminating any redundant elements

Is there a way to merge these array sets while ensuring that duplicate values are removed? I am unsure if lodash provides a solution for this specific scenario where the arrays are nested. Most of the solutions I have come across assume flat arrays. Any ...