0

I want to read from a json file and use its values to draw triangles. While being in the routine i can print out the value, outside of it, it won't work any more. My code:

faces=new Array(40000);
$.getJSON('file.json', function(data) {
   $.each(data.faces, function(i, f) {
faces[i]=new Array(3);
faces[i][1]=data.faces[i].f1;
faces[i][2]=data.faces[i].f2;
faces[i][3]=data.faces[i].f3;
 //alert(faces[1][1]); works here
 });
 });
 //alert(faces[1][1]); doesn't work here, console says faces[1][1] is undefined

How can I fix this?

4 Answers 4

2

The call to $.getJSON is asynchronous, you only have your faces array populated inside the callback as you already noticed.

What you could do is:

faces=new Array(40000);
$.getJSON('file.json', function(data) {
  $.each(data.faces, function(i, f) {
    faces[i]=new Array(3);
    faces[i][1]=data.faces[i].f1;
    faces[i][2]=data.faces[i].f2;
    faces[i][3]=data.faces[i].f3;
     //alert(faces[1][1]); works here
  });
  someFunction();
});

someFunction() {
  alert(faces[1][1]);
}

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

0

That happens because getJSON is async.

try to use the jquery ajax method with async property defined.

   $.ajax({
        type: "GET",
        url: remote_url,
        async: false,
        success : function(data) {
            remote = data;
        }
    });

Comments

0

Your call to actually get the JSON, in the second case, is taking longer than it takes to get to the point of usage outside of the "success"/"complete" callback, due to the asynchronicity of getJSON, so the value(s) is/are naturally undefined until the function returns, hence the "success"/"complete" function.

Comments

-1

Simple change,

faces=new Array(40000);
$.getJSON('file.json', function(data) {
 $.each(data.faces, function(i, f) {
  faces[i]=new Array(3);
  faces[i][1]=f.f1;
  faces[i][2]=f.f2;
  faces[i][3]=f.f3;
 });
});

Use f instead of data.faces inside $.each

1 Comment

what is wrong in it u need to use data.faces inside each function since u already assigned its each index in a variable f

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.