How to import data with JSON?

I am relatively new to JavaScript and I am trying to learn to extract data from a .json file. Is the code below correct?

  • <!DOCTYPE html> <html> <head> </head> <body> <h2>JSON Object Creation in JavaScript</h2> <p> First Name: <span id="fname"></span><br /> Last Name: <span id="lname"></span><br /> </p> <script type="text/javascript" src="JSONFile.json"></script> <script> var xhr = new XMLHttpRequest(); xhr.open("GET", "JSONFile.json", true); xhr.send(null); alert("j"); var jsonString = JSON.parse(xhr.responseText); alert("j"); alert(jsonString.properties.id.description); document.getElementById("fname").innerHTML= jsonString.properties.id.description; alert(jsonString.properties.id.description); </script> </body> </html> Here, I am creating an XMLHttpRequest object and trying to fetch the data from the .json file. I have read a lot of blogs and finally came up with this code. The pproblem here is that - if i remove the alert statements in the code, the "jsonString" becomes undefined. with all the alert statements, the code is working properly. What can be the issue over here? I have tested this on Firefox 29.0.1 (firebug installed). P.S. : The code does not work at all in Google chrome.

  • Answer:

    You need to move the response handling code to the Ajax success callback. var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { // Ready state 4 means the request is done and // 200 is a successful return if (xhr.readyState === 4 && xhr.status === 200) { var jsonString = JSON.parse(xhr.responseText); document.getElementById("fname").innerHTML= jsonString.properties.id.description; } }; xhr.open("GET", "JSONFile.json", true); xhr.send(null); Since alert() statements block the execution of the code, the Ajax call meanwhile gets completed and your code works fine. Due to asynchronous processing (you can try setting the third parameter to false for the xhr.open() call to make the request synchronous - which beats the purpose of using Ajax and is not recommended), the XHR response handling part in your original code gets processed without waiting for the response; hence the callback.

Kumar Bhot at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.