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
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.
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.