Building accordion menus on the fly

Building accordion menus on the fly

 Hello,

On my website I have a menu that lists all the available categories that a user can read, when the user clicks a category some ajax is fired that runs a database and returns all the categories content in the form of thumbnail images, if the user then clicks that category link again the accordion should be deleted from the page, I have it working if there is only one accordion on screen but if add a second it stops the first being an accordion could look at my code and tell me where I am going wrong please?


   
  1.  $("a.navlink").click(function(ev) {
    var url = $(this).attr("href")
    var id = $(this).attr("id")
    ev.preventDefault();
    if(!$(this).hasClass('saved')) {
    //$("a.navlink").addClass('active')
    $.ajax ({
    url: url,
    type: "POST",
    data: "method=add&id="+id,
    success: function (html) {
    $('#accordion').accordion('destroy');
    $("#accordion").append(html);
    $('#accordion').accordion({
    header:'h2.'+id,
    collapsible:true
    });
    $("a.navlink").addClass('saved');
    }
    });
    } else if($("a.navlink").hasClass('saved')) {
    $.ajax ({
    url: url,
    type: "POST",
    data: "method=delete",
    success: function (html) {
    $("a.navlink").removeClass('saved');
    $('#accordion').find('.'+id).remove();
    }
    });
    }
    });






























And also the HTML/PHP that builds the accordions
      
  1.  <?php
    //var_dump($_POST);
    if(isset($content)) {
    foreach($category_name as $k => $v) {
    echo "<h2 class=".$this->input->post('id')."><a href='#'>$v[category_name]</a></h2>";
    echo "<div class='$v[category_name]'>";
    }
    $replace = array(".", "png", "gif", "jpg");
    $count = 0;
    foreach($content as $k=>$v) {
    $count ++;
    $image_name = str_replace($replace, "", $v['image_name']);
    echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
    echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
    echo "</a>";
    }
    echo "</div>";
    //die(var_dump($content));
    }

    if(isset($favourites_category)) {
    echo "<h2 class=".$this->input->post('id')."><a href='#'>$favourites_category</a></h2>";
    echo "<div class=".strtolower($favourites_category).">";
    $replace = array(".", "png", "gif", "jpg");
    $count = 0;
    foreach($favourites as $k=>$v) {
    $count ++;
    $image_name = str_replace($replace, "", $v['image_name']);
    echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
    echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
    echo "</a>";
    }
    echo "</div>";
    }
    ?>

































I would really appreciate if someone could point me in the right direction