0

I am trying to make a simple sample previewer for my client project. The list of samples are stored in a JSON file. but the trouble is that I am not too familiar with using JSON, or programming itself, to be honest. I have written a short test code to see if this JSON file works well, but although I can access sampleData variable from firebug console, the document.write(sampleData.length); line seems to be unable to access sampleData for some reason. The error shows:

TypeError: sampleData is undefined

I suspect it has to do with variable scopes, but I am not sure.

<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    var sampleData;
    $.getJSON('res/Samples.json',function(data){
        sampleData=data;
    });
    document.write(sampleData.length);
</script>

What should I do to make the sampleData variable to work with the rest of the code?
I'm sorry I cannot disclose the contents of the json file. It contains an array of objects containing information of the products. it looks like

[
    {
    "aaa" : 000000;
    },
    {
    "bbb" : 111111;
    },
    {
    "ccc" : 222222;
    }
]

It's a quite generic form of JSON file, as far as I can tell.

1
  • This question is similar to: How do I return the response from an asynchronous call?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 12, 2024 at 10:53

5 Answers 5

4

Your code's fine, but $.getJSON just starts the process of getting the JSON file, and then allows your code to continue, calling document.write. The callback to $.getJSON is called later, after your document.write call. Instead, trigger any subsequent code you want to trigger from within the callback.

You can't usefully use document.write in this situation. You can use the DOM, though, and jQuery's various DOM wrapper functions. For instance:

$.getJSON('res/Samples.json',function(data){
    $("<p>").html(data.length).appendTo(document.body);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I ended up using ajax statement with async parameter instead...I know it sort of breaks the meaning of ajax, but whatever... :)
@K.H.: More importantly, it locks up the UI of the browser while the request is in progress, making for a poor UX. If at all possible, embrace the asynchronousness. :-) But I'm glad that helped.
2

It's due to the async response from $.getJSON.

var sampleData;
$.getJSON('res/Samples.json', function(data) {
  sampleData = data; // This is occurring after the document.write
});
document.write(sampleData.length);

This is essentially the same as:

var sampleData;
setTimeout(function() {
  sampleData = 'Some data'; // This is occurring after the document.write
}, 100);
document.write(sampleData.length);

You could move the document.write to the response handler but as noted below it does have its drawbacks:

var sampleData;
$.getJSON('res/Samples.json', function(data) {
  document.write(sampleData.length); // This would replace the page contents
});

3 Comments

"You could move the document.write to the response handler:" You could, but it would wipe out the content of the page and replace it with just that number. After initial parsing, using document.write implicitly calls document.open, wiping out the page.
True, but that's a different problem. Best way to learn how things work is to see how they break. :)
Thanks for pointing out the document.write thing. I tried that before I came back to this post, and had to learn it the hard way...
1

It happens asynchronously, so you need to call document.write in the async call itself:

var sampleData;
$.getJSON('res/Samples.json',function(data){
    sampleData = data;
    document.write(sampleData.length);
});

Also, if you're using document.write in your production code to write to the page, I would suggest against it. If you used document.write in the above example just for debugging purposes (to figure out why it wasn't working), I would suggest using console.log instead. Much easier.

Comments

1

$.getJSON is an async function and when you do document.write(sampleData.length);, sampleData is not populated yet.

You must to do:

$.getJSON('res/Samples.json',function(data){
   sampleData=data;
   document.write(sampleData.length);
});

Comments

0

Well is reason is you call the sampleData.length before the ajax call return the values you need to put the document.write(sampleData.length); inside the ajax function

<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    var sampleData;
    $.getJSON('res/Samples.json',function(data){
        sampleData=data;
        document.write(sampleData.length);
    });

</script>

Comments

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.