0

I've got an array of dashboard objects to add to a page, but I've found that JavaScript powers through the array far faster than my Ajax endpoint can respond, so it winds up that all of the callbacks try to update the final element.

Loop:

for( i=0, l=dashboards.length; i<l; i++ ){
    $("#dashboard-container").append(template(dashboards[i]["templateargs"]));
    var cur_id = dashboards[i]["templateargs"]["dashboard-id"];
    var chart = $("#"+cur_id+"-chart");
    var table = $("#"+cur_id+"-table tbody");
    $.ajax({
        type: "GET",
        url: dashboards[i]["ajaxurl"],
        error: function() { alert('AJAX error'); },
        success: dashboards[i]["callback"]
    });
}

Example callback:

function(data) {
    $.plot(chart, data, chart_options);
    for(i=0;i<data.length;i++) {
        table.append("<tr><td>"+data[i]['label']+"</td><td>"+data[i]['data']+"</td></tr>");
    }
}

I'm not all that great with event-driven programming, and JS's variable scoping is odd to me as well. How can I get these panels updating properly?

Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • You need to define `chart chart_options` and `table` inside the callback. Otherwise, you're just referencing the last `chart chart_options` and `table`. – Kevin B Mar 19 '15 at 20:57

1 Answers1

0

I have not tested this but I believe it will work. You need to chain your callbacks so that i is only incremented once the callback from the previous ajax request has fired.

    for( i=0, l=dashboards.length; i<l; i++ ){
        $("#dashboard-container").append(template(dashboards[i]["templateargs"]));
        var cur_id = dashboards[i]["templateargs"]["dashboard-id"];
        var chart = $("#"+cur_id+"-chart");
        var table = $("#"+cur_id+"-table tbody");
    }
    start_ajax_chain(0,dashboards.length,dashboards);

    function start_ajax_chain(i,l,dashboards){
    if(i<l){
       $.ajax({
               type: "GET",
               url: dashboards[i]["ajaxurl"],
               error: function() { alert('AJAX error'); },
               success: function(data){
                         callback = dashboards[i]["callback"];  
                         callback(data);
                         i++;
                         start_ajax_chain(i,l,dashboards);}
             });

         }
    }
Isaac Ray
  • 1,351
  • 9
  • 17