0

Hi I have the below 2 functions. If I console.log(data) within loadJSON, it works correctly but when I log data in serviceDesc, the value is undefined. The data itself is correct when logged in loadJSON but I don't know why it becomes undefined. Can anyone point me in the right direction?

function serviceDesc(){
    var data = loadJSON('json/services.json',
               function(xhr){console.log(xhr);});
    console.log(data);
}

function loadJSON(path, error){
    var xhr = new XMLHttpRequest();
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    } else{
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.onreadystatechange = function(){
        if(xhr.readyState == XMLHttpRequest.DONE){
            if(xhr.status == 200){
                var data = JSON.parse(xhr.responseText);
                return data;
            } else{
                if(error) error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}
  • 1
    You can not really return from `ajax` as it is asynchronous. Use success callback as well as you have used error callback. Try this: https://jsfiddle.net/rayon_1990/5ar52eop/ – Rayon Jan 04 '16 at 04:29
  • oh i see, new to javascript. thanks! –  Jan 04 '16 at 04:30

0 Answers0