skip to Main Content

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"
    }
]

2

Answers


  1. 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
    });
    
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search