0

I am trying to load JSON file in my local server, I created function, name is getServiceData, in this function, I am loading JSON file by creating ajax call, getServiceData function return response to a variable, variable name is gserviceData. now I am printing this variable in console, first it is coming 'undefined' and second time automatically data is printing. Please try to help me on this.

JavaScript (main.js):

function getServiceData() {   
  debugger;
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', 'data/service.json', true); // Replace 'my_data' with the path to your file
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {  
      debugger;
      // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
      alert("calling");
      console.log(xobj);
      return JSON.parse(xobj.response);
    }
  };
  xobj.send(null);  
}


var gserviceData = getServiceData();

JSON (service.json):

[   {
        "WS": "Web Strategy",
        "WD": "Web design"
    },
    {
        "WD": "Web Development",
        "WP": "Web Performence"
    },
    {
        "WE": "Web Enhancement",
        "WH": "Web Hosting"
    },
    {
        "WS": "Web Support",
        "WA": "Web Applications"
    },
    {
        "MA": "Mobile Applications",
        "CHS": "Could Hosting Services"
    },
    {
        "PDC": "Product Development Consulting",
        "SEO": "Search Engine Optimization"
    }
]
Alexander Shtang
  • 1,819
  • 4
  • 15
  • 24
Venkat B
  • 41
  • 1
  • 1
  • 5

2 Answers2

0

Hi you are trying to get return on finish to ajax call but java script is not wait for ajax so it will automaticaly return undefined.So in this situation you can use promise or callback function.

  function getServiceData(callback) {   debugger;
                    var xobj = new XMLHttpRequest();
                        xobj.overrideMimeType("application/json");
                    xobj.open('GET', 'data/service.json', true); // Replace 'my_data' with the path to your file
                    xobj.onreadystatechange = function () {
                          if (xobj.readyState == 4 && xobj.status == "200") {  debugger;
                            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
                            alert("calling");
                            console.log(xobj);
                             callback(JSON.parse(xobj.response));
                          }
                    };
                    xobj.send(null);  
                 }


  getServiceData(function (data) {
   ////Write your logic here
});
Devraj verma
  • 407
  • 3
  • 14
0

I have edited your code a bit. Should look like this. Remember when dealing with async operation, the result might take a while so you need to attach a callback to execute when the result is ready.

function getServiceData(done) {
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType('application/json');
  xobj.open('GET', 'data/service.json', true);
  xobj.onreadystatechange = function () {
    if(xobj.readyState === 4 && xobj.status === '200') {
      return done(JSON.parse(xobj.responseText));
    }
    done(null);
  };
  xobj.send(null);  
}

function onDone(data) {
  console.log(data);
}

getServiceData(onDone);
CodeLover
  • 571
  • 2
  • 11
  • Failed to load file:///E:/Xampp/htdocs/tsb/data/service.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. – Venkat B Feb 19 '18 at 05:34
  • That is another topic which you can read here https://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local – CodeLover Feb 19 '18 at 05:37