0

The code below does not seem to be able to concatenate a JSON result into a string, does anyone have any idea why?

function wordCloud(filename)
{
    var file = filename;
    var text = " ";
    $.getJSON(file, function(data) {
        $.each(data, function(key, val) {
            text = text.concat(val.toString());
        });
    });
    console.log(text);
 }

Thanks

user1840255
  • 287
  • 1
  • 6
  • 15
  • 4
    `console.log(text);` is executed **before** the success callback is called. Ajax is **asynchronous**. Please have a look at http://stackoverflow.com/a/14220323/218196. – Felix Kling Feb 16 '13 at 20:32
  • Ahhh does that mean it is still working? Should I include a delay of some sort? – user1840255 Feb 16 '13 at 20:33
  • 1
    No, you should put `console.log(text)` inside the callback. – Felix Kling Feb 16 '13 at 20:33
  • If I wanted to use the text variable later on in another routine would I have to use a delay though? thanks for your help though :) – user1840255 Feb 16 '13 at 20:34
  • 1
    Especially then you should read the other question I linked to. Here it is again: http://stackoverflow.com/q/14220321/218196. – Felix Kling Feb 16 '13 at 20:35
  • And using a delay is not the appropriate thing as you dont know exactly when your json data will be received (depends on factors like speed of internet connection, server status, etc) – gopi1410 Feb 16 '13 at 20:36

1 Answers1

1

It would execute fine, just you have to add your console.log within the get statement because otherwise, the getJSON code runs asynchronously and in the meantime when the control reaches the console.log statement, text is yet empty. So you have to modify your code in the following way:

$.getJSON(file, function(data) {
    $.each(data, function(key, val) {
        text = text.concat(val.toString());
    });
    console.log(text);
});
gopi1410
  • 6,567
  • 9
  • 41
  • 75