1

I have a one variable file like this.

var geography = [
                    { id:"Country",   header:"",    width:150},
                    { id:"Capital",    header:"Capital", width:150},
                    { id:"Falg",   header:"Falg", width:150},
                    { id:"Language",   header:"Language", width:150},
                    {id:"Population", header:"Population", width:150},
                ],

Now I wanted to load this data from the json. I placed this data into JSON file and Using this code.

getGeography function(){
        var geography;
        var xmlhttp = new XMLHttpRequest();   
        xmlhttp.open("GET", "data.json",true);
    }

Now from here how to store into a variable and return that.

David
  • 4,266
  • 8
  • 34
  • 69
  • Use [onreadystatechange](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange) i.e. `xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) { geography = xmlhttp.responseText; } };` – Satpal Oct 20 '17 at 06:38

3 Answers3

3

It should be read when the ready state of xmlhttp is 4 and response status is 200. You should parse the response with JSON.parse(). However you can't return the value from the function. Because XMLHTTPRequest is asynchronous by default.

function getGeography() {
 var geography;
 var xmlhttp = new XMLHttpRequest();   
 xmlhttp.open("GET", "data.json",true);
 xmlhttp.onreadystatechange = function () { 
  if(xmlhttp.readyState === 4 && xmlhttp.status === 200) { 
   geography = JSON.parse(xmlhttp.responseText;) 
  }
 }
}

Instead of returning geography you have to programmatically read the value of geography when the AJAX request is complete. Something like this (read this):

Instead of writing code like this:

function anotherFunc() {
 var geography = getGeography();
 thenDoSomething(geography);
}

Write like this:

function anotherFunc() {
 getGeography();
}
function getGeography() {
 var geography;
 var xmlhttp = new XMLHttpRequest();   
 xmlhttp.open("GET", "data.json",true);
 xmlhttp.onreadystatechange = function () { 
  if(xmlhttp.readyState === 4 && xmlhttp.status === 200) { 
   geography = JSON.parse(xmlhttp.responseText);
   thenDoSomething(geography); 
  }
 }
}

It's like handing over the control of execution of rest of the code to getGeography() function, instead of expecting a return value from the function and then using that value. The getGeography() function resumes execution of rest of the code with the value received from AJAX response, when the AJAX call completes.

sribasu
  • 680
  • 2
  • 6
  • 24
  • DO I need to declare `geography` as an array ? – David Oct 20 '17 at 06:51
  • 2
    No, javascript does not require types defined. with `var geography;` you declare variable and assign `undefined` value. You can assign whatever you want and then assign whatever else. The type will be changed automatically. – Lukas Liesis Oct 20 '17 at 06:57
  • In this case also I am gettong status is getting 0 instead of 200 – David Oct 20 '17 at 07:13
  • @David it could be due to several reasons. Read [this](https://stackoverflow.com/a/10173639/2168552) and [this](https://stackoverflow.com/a/26451773/2168552) – sribasu Oct 21 '17 at 18:36
0

I'm not a fan of jQuery but in this case, you would probably benefit from this.

$.get( "ajax/test.html", function( data ) {
  // data is your result
  console.log(data);
  console.log(JSON.parse(data));
});

https://api.jquery.com/jquery.get/

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
0

Here is how to use XMLHttRequest() :

<script>
    const req = new XMLHttpRequest();
    var geography = [];
    req.onreadystatechange = function(event) {
        // XMLHttpRequest.DONE === 4
        if (this.readyState === XMLHttpRequest.DONE) {
            if (this.status === 200) {
                geography = JSON.parse(this.responseText);
                console.log(geography);
                alert("Great Success : check console !");
            } else {
                alert("Something has gone really Bad !");
            }
        }
    };

    req.open('GET', 'data.json', true);
    req.send(null);

Be careful to use correct JSON :

[
    {"id":"Country","header":"","width":150},
    { "id":"Capital","header":"Capital", "width":150},
    { "id":"Falg","header":"Falg","width":150},
    { "id":"Language","header":"Language", "width":150},
    { "id":"Population", "header":"Population", "width":150}
]
PhilMaGeo
  • 551
  • 6
  • 8
  • status is getting 0 instead of 200 – David Oct 20 '17 at 07:07
  • Do you use a web server ? You should not open your html file locally I mean via the file protocol. Use a web server. You can use "Web server for chrome" for instance, which is a chrome addon. I tested my example with it and it works fine :-) – PhilMaGeo Oct 20 '17 at 07:28