0

I'd like to do something like:

var content = "";
$.getJSON("/plants", function(result) {
    $.each(result.plants), function() {
        content += "<tr><td>"+this.plant_name+"</td></tr>";
    });
});
$("#plant_table").append(content);

By the time I do the append at the last line, content is empty. I'd guess it's because of the scope of the content variable, but I'm unfamiliar with how to remedy this.

Thanks in advance.

Steven
  • 1,049
  • 2
  • 14
  • 32

2 Answers2

1

As @dandavis and probably the other person who I just see answered this said, try:

var content = "";
$.getJSON("/plants", function(result) {
    $.each(result.plants), function() {
        content += "<tr><td>"+this.plant_name+"</td></tr>";
    });
    $("#plant_table").append(content);
});

The $.getJSON is non-blocking / asynchronous, thus your .append() is occurring prior to $.getJSON() succeeding and manipulating the variable named content.

BjornJohnson
  • 332
  • 1
  • 8
0

You have to put the content $("#plant_table").append(content); in getJSON function.
Because if the content is out of getJSON function, it is ran firstly. It is synchronize problem. :)

Sea guy
  • 178
  • 1
  • 2
  • 10