0

I'm using the "Ion.RangeSlider" library. I'm trying to load the values via JSON but can't get the slider to accept the "from" field. I can't have the value hardcoded since the user can change it.

$(function(){
  'use strict'
  $('#rt').ionRangeSlider({
    min: 100,
    max: 100000,
    step: 10,
    from: loaddata(), -> Doesn't get the data from the function even though it prints it to the console.
    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; -> Changing the value of the slider doesn't work as well
      console.log(myObj.response_time); -> Prints 2000 to the console
      return myObj.response_time;
    }
  };
  xmlhttp.open("GET", "api/settings.json", true);
  xmlhttp.send();
}

My json file:

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

1 Answers1

0

loaddata() doesn't return anything, that's why. AJAX requests are asynchronous. The data returned from the server arrives in the onreadystatechange callback function at some later time, whenever the server has processed the request and provided a response. The data is not, and cannot, be returned from loaddata() - not least because the loaddata function has already finished when the callback is executed.

You've attempted to return data from the onreadystatechange callback, but the callback function is executed by code in the XmlHttpRequest object, so the returned value goes back into there - but that object is not interested in it, and your code cannot get access to it.

You will to need to fetch the data first, and then from the onreadystagechange callback you can run a function to initialise the rangeslider, passing in the downloaded data.

e.g. something like this:

$(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: "
  });
}

See also How do I return the response from an asynchronous call?.

ADyson
  • 57,178
  • 14
  • 51
  • 63