'Function gets called only on the second click [duplicate]

I have a button that needs to execute a function. This function reads a json file from my machine and then parses it. It works all fine but the problem is that the button has to be clicked two times in order to get fired every function that has in it...

//function 

var testJson;
function GetJsonData(FileName){
   var client = new XMLHttpRequest();

   client.open('GET', './DDListFiles/'+FileName+'?_=' + new Date().getTime());

   client.onreadystatechange = function() {
   testjson = client.responseText;
   }
   client.send();
   return testjson;
}
//button event listener on click
document.getElementByID("mybtn").addEventListener("click",function(){

var getData = JSON.parse(GetJsonData('myfile.json'));

console.log("Data=",getData[0].Name);
})

Can you please help me sort this out?

The error I get on the first click is:

Unexpected token u in JSON at position 0

But there is no typo or anything wrong with the file.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source