0

I can't seem to get the accordion menu to apply to new html code that's been appended using jquery. To make things more complicated I'm extracting data from mysql server using the ajax function and a for loop. When I do this, I can only apply the accordion menu to the first header.

$(document).ready(function(){
    $.ajax({                                      
      url: 'database/api.php', data: "", dataType: 'json',  success: function(rows)        
      {
        for (var i in rows)
        {
          var row = rows[i];          
          var code = row[0];
          var process = row[1];

          $('#accordion').append("<h3>"+code+"</h3><div><p>Process: "+process+"</p></div>");


        } 
      } 
    });
    $("#accordion").accordion({collapsible: true, active: false});
});
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Musa Jun 10 '13 at 01:19
  • So you're calling `$("#accordion").accordion()` before there is any content? Or does `#accordion` start out with stuff and you're just adding more? – mu is too short Jun 10 '13 at 01:27
  • I've tried both. In the example I'm appending it to
    but I have done it with contents included.
    – Braden Jageman Jun 11 '13 at 22:02

1 Answers1

1

Unless you specify, the ajax request is done asynchronously. Which means it will start the ajax request and just skip to the next statement, even if it hasn't finished. So your initializing the accordion before your data has been appended. Move the accordion statement into success, after the for loop.

Also, don't keep appending html to the DOM. Collect it all in a variable and do it one time.

$(document).ready(function(){
$.ajax({                                      
  url: 'database/api.php', data: "", dataType: 'json',  success: function(rows)        
  {
    var innerHtml = "";//variable to store what you want to add
    for (var i in rows)
    {
      var row = rows[i];          
      var code = row[0];
      var process = row[1];

      innerHtml += "<h3>"+code+"</h3><div><p>Process: "+process+"</p></div>";


    }

    $("#accordion").append(innerHtml).accordion({collapsible: true, active: false});
  } 
});

});
James
  • 1,562
  • 15
  • 23