0

Background: I am attempting to retrieve data, using AJAX, and assign it to a variable. I have tried to set the AJAX request to synchronous, but Firefox will not allow it.

Question: How can I make certain all the data is received?

function search(){
    var data = [];
    this.init = function(){
        data = getData({"url":"/imglib/Inventory/cache/2335/VehInv.js"});
        console.log(data);  // Returns as 'undefined'. Possibly because of asynchronous call?
    };
    var d = new Date();
    function getData(url){
        var xhttp: new XMLHttpRequest();
        var dataURL = url + '?v=' String(d.getTime());
        xhttp.onreadystatechange = function(){
            if(this.readyState = 4 && this.status == 200){
                var r = this.responseText;
                var s = r.indexOf('[') + 1;
                var e = r.indexOf(']');
                var jsonData = JSON.parse("[" + r.slice(s,e) + "]");
                return jsonData;
            }
        };
        xhttp.open("GET", dataURL, true);
        xhttp.send();
    }
};
H0nd0
  • 1
  • 1
  • Sounds like you may want to look at Promises: http://bluebirdjs.com/docs/getting-started.html – mherzig Oct 05 '16 at 00:03
  • @mherzig Thank you. I really appreciate the input. Unfortunately, the environment I will be deploying this in will require the use of pure javascript. – H0nd0 Oct 05 '16 at 00:09
  • Or move the `console.log(data)` within the `ondreadystatechange` function... and do it `console.log(jsonData)`. The reason why you get undefined it is because AJAX nature is async. From the `XMLHttpRequest` documentation the default value for `async` is true... have you try to set it to `false`? `xhttp.open('GET', dataUrl, false)` – David Espino Oct 05 '16 at 00:10
  • @DavidEspino Firefox is not allowing synchronous calls; it generates a console error. – H0nd0 Oct 05 '16 at 03:20

2 Answers2

0

you have to use a callback when working with asynchronous stuff..

function search(){
    this.init = function(){
        getData("http://www.petesrvvt.com/imglib/Inventory/cache/2335/VehInv.js", function(data){
            console.log(data);  // Returns as 'undefined'. Possibly because of asynchronous call?
        });
    };
    var d = new Date();
    function getData(url, callback){
        var xhttp: new XMLHttpRequest();
        var dataURL = url + '?v=' String(d.getTime());
        xhttp.onreadystatechange = function(){
            if(this.readyState = 4 && this.status == 200){
                var r = this.responseText;
                var s = r.indexOf('[') + 1;
                var e = r.indexOf(']');
                var jsonData = JSON.parse("[" + r.slice(s,e) + "]");
                callback(jsonData);
            }
        };
        xhttp.open("GET", dataURL, true);
        xhttp.send();
    }
};
Robert Parham
  • 704
  • 3
  • 10
0

Call the function that will deal with the data from the function invoked on "onreadystatechange". The reason it doesn't work is that the variable "data" isn't defined with the result of the async query when you are attempting to use it.

(function search() {
  var data = [];
  this.init = function() {
    data = getData({
      "url": "http://www.petesrvvt.com/imglib/Inventory/cache/2335/VehInv.js"
    });
    // This is definitely caused by the asynchronous XMLHttpRequest  
    //console.log(data); // This needs to be moved to the callback that is invoked when the request completes. See below
  };
  var d = new Date();

  function getData(url) {
    var xhttp: new XMLHttpRequest();
    var dataURL = url + '?v='
    String(d.getTime());
    xhttp.onreadystatechange = function() {
      if (this.readyState = 4 && this.status == 200) {
        var r = this.responseText;
        var s = r.indexOf('[') + 1;
        var e = r.indexOf(']');
        var jsonData = JSON.parse("[" + r.slice(s, e) + "]");
        // This is how you be sure you get your data
        console.log(jsonData);
      }
    };
    xhttp.open("GET", dataURL, true);
    xhttp.send();
  }
})();
Kent Anderson
  • 486
  • 2
  • 16