-1

I wanted to get some data from a .json file and use it in another js file.through tutorial i understood that u need to use a ajax function to call the .json file.I used the following function to that however the alert(results) doesnt show any value.can somone plss help???

var results;
var data;
function ajax_get_json() {

    var hr = new XMLHttpRequest();
    hr.open("GET", "Test2.json", true);
    hr.setRequestHeader("Content-type", "application/json", true);
    hr.onreadystatechange = function() {
        if (hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            //results=document.getElementById("results");                              
            //results.innerHTML=data.user + " " +data.country;
            results = data.user;

        }
    }

    hr.send(null);

    //results.innerHTML = "requesting...";
    }
ajax_get_json()
    alert(results);
Josh Harrison
  • 5,927
  • 1
  • 30
  • 44
user3292309
  • 45
  • 1
  • 6
  • 1
    Why would you need AJAX to load a JSON file? And also, now that you are using AJAX, AJAX is asynchronous, so by the time you call the alert, AJAX isn't ready yet. – putvande Feb 10 '14 at 09:58
  • 1
    `hr.setRequestHeader("Content-type", "application/json", true);` says that you are *sending* JSON *to the server*. You aren't. You aren't even making a POST request. Take that out. – Quentin Feb 10 '14 at 10:05

5 Answers5

1

Because the AJAX request is asynchronous, the browser doesn't wait for it to complete before carrying on executing other code. So alert is called before the request has completed.

Make your function reusable, allowing you to request any file, and pass in a callback function to be executed on completion:

function ajax_get_json(file, callback) {

    var hr = new XMLHttpRequest();
    hr.open("GET", file, true);
    hr.onreadystatechange = function() {
        var data, results;
        if(hr.readyState == 4 && hr.status == 200) {
            data=JSON.parse(hr.responseText);
            results=data.user;
            callback(results);
        }
    }

    hr.send(null);

}

// request a file and do something with the contents when complete
ajax_get_json("Test2.json", function(results) {
    alert(results);
});

// request a different file and do something else with the contents
ajax_get_json("Test3.json", function(results) {
    console.log(results);
});

EDIT

Just seen in another comment that you want to use the results in a different file.

Include the ajax_get_json function in some kind of helpers.js file, and then you can call ajax_get_json in your other JS files.

Or, if you really need to use the same results across different scripts, you'll have to store the results in window:

ajax_get_json("Test2.json", function(results) {
    alert(results);
    window.resultsCache = results;
    // window.resultsCache now available to all scripts on the page
});
Josh Harrison
  • 5,927
  • 1
  • 30
  • 44
  • I tried using the function you suggested like u suggested however wen i assign the value like so in another.js file thejsonvalue=window.resultsCache; and do an alert(thejsonvalue) it shos undefined.the thing is the value is only retained within the ajax_get_json() function after which it seems to lose the value – user3292309 Feb 10 '14 at 10:50
  • Adding it as a property of `window` definitely exposes it to all scripts on the page. The problem will probably be the same as your original problem - when you try to access `window.resultsCache` in the other js file, the request still hasn't completed. Do you need to use the results of `ajax_get_json` in more than one file? If not, just call `ajax_get_json` with a callback once, where you need it, and don't bother caching it to `window`. – Josh Harrison Feb 10 '14 at 10:55
  • what i basicaly want to acheive is to use the value in a .json file to position sprites using the the sprite.add()method.so basicaly i need the x and y positions stored in the json file like so game.add.sprite(xvalue,yvalue,name) wer xvalue and yvalue are values from a json file.so u see i need the actualy use the value in the function not just display it – user3292309 Feb 10 '14 at 10:58
  • If you need help using the results of the JSON file, it's another question, or read a tutorial. I hope my code above has answered your problem on this page :) – Josh Harrison Feb 10 '14 at 11:04
  • Ill try staying within function bounds then.thx – user3292309 Feb 10 '14 at 11:25
  • I think that will be the best bet for you. Please consider accepting the answer if it helped you. – Josh Harrison Feb 10 '14 at 11:33
0

Your alert is executed before the AJAX onreadystatechange callback.

Try to move it right after the results=data.user; line, inside the callback.

sdabet
  • 18,360
  • 11
  • 89
  • 158
0

AJAX is Asynchronous. So by the time your AJAX request is done, your alert has already been called. You need to place the alert inside the AJAX function:

var results;
var data;

function ajax_get_json() {
    var hr = new XMLHttpRequest();
    hr.open("GET", "Test2.json", true);
    hr.setRequestHeader("Content-type", "application/json", true);
    hr.onreadystatechange = function () {
        if (hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            //results=document.getElementById("results");                               
            //results.innerHTML=data.user + " " +data.country;
            results = data.user;
            alert(results);
        }
    }
    hr.send(null);
    //results.innerHTML = "requesting...";
}
ajax_get_json()
putvande
  • 15,068
  • 3
  • 34
  • 50
  • Well Actualy I want to use the data.user in another .js file so I want it to retain its value.thats y I want the alert statement to work outside the ajax.I want the results value(or data.user) to be used outside – user3292309 Feb 10 '14 at 10:17
0

What is happening is this. You declare data and results, Make your ajax call, create an alert, your ajax call returns. As the alert is created before the ajax call completes your alert box shows nothing.

Ajax calls are done asynchronously, so you would need to move the alert in to your callback

var results;
var data;
function ajax_get_json(){

   var hr = new XMLHttpRequest();
   hr.open("GET", "Test2.json", true);
   hr.setRequestHeader("Content-type", "application/json",true);
   hr.onreadystatechange = function() {
       if(hr.readyState == 4 && hr.status == 200) {
           var data=JSON.parse(hr.responseText);
           alert(data.user);

       }
  }
  hr.send(null);
}
ajax_get_json()
Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103
  • Well Actualy I want to use the data.user in another .js file so I want it to retain its value.thats y I want the alert statement to work outside the ajax – user3292309 Feb 10 '14 at 10:15
  • Not easily possible. Because you are working in an asynchronous way you have to think about the problem differently. Zougen Moriver's answer provides you with a better way. – Jim Jeffries Feb 10 '14 at 10:25
-1

To get Json i have used ajax call and it worked. here is a sample

$.ajax({
    url: "sample.json",
    dataType: 'json',
    contentType:"application/json",
    success: function(response) {
        //here you can use the response
            //response can be passed to what ever js file you need.

    },
    error: function(response1){
            alert('response error')
    }
});

here sample.json is a local file instead you can use the url where the json is present

I hope this will help you

Strikers
  • 4,698
  • 2
  • 28
  • 58
  • This requires jQuery - [Unless a tag for a framework/library is also included, a pure JavaScript answer is expected.](http://stackoverflow.com/questions/tagged/javascript) – Josh Harrison Feb 10 '14 at 10:22
  • I tried your method too by downloading jquery but it shows me a response error msg – user3292309 Feb 10 '14 at 11:07
  • response error may come if you have a issue with the JSON. once check if your JSON is valid or not – Strikers Feb 10 '14 at 12:09