Ayan Ayan - 5 months ago 8
jQuery Question

How to stop jquery from removing child elements when inserting data via ajax

I am using this following code to insert data into an html structure but only either or of the following gets displayed. It seems to me that while I insert data via Ajax the child elements are getting removed by that. What to do so that I dont need to change the structure?

JS

<script type="text/javascript">
$(document).ready(function(){
$("#list").html('<div id="loader"><i class="fa fa-refresh fa-fw fa-5x fa-spin" aria-hidden="true"></i><br>Waiting...</div>');
setInterval(function(){
$.ajax({
type: "GET",
url: "generate_list.php",
dataType:"json",
cache: false,
success: function(result){
$('#list').html(result.heading);
$('#list ul').html(result.list);
}
});
}, 1000);
});
</script>


HTML

<div id="list">
<ul>
</ul>
</div>


PHP SNIPPET

if($count > 0){
echo json_encode(array('heading' => '<div id="found">Here is all!</div>', 'list' => $thelist));
}
else{
echo json_encode(array('heading' => '<div id="empty_storage"><img src="icon.png"><br>Its lonely here!</div>', 'list' => $thelist));
}

Answer

The ajax callback isn't what is removing your html (although it would if it were still there), your first line:

$("#list").html('<div id="loader"><i class="fa fa-refresh fa-fw fa-5x fa-spin" aria-hidden="true"></i><br>Waiting...</div>');

Is actually removing your <ul> from your #list element... which is fine, if you add it back. Assuming results.heading is an h1 tag (or similar) and results.list is a bunch of li elements, your ajax callback could look like this:

$('#list').html(result.heading);
$('#list').append($('<ul>').append(result.list));

Also: If you want your loader to show between each interval... you could do this (or something similar depending on how it looks - this would put the loader icon at the bottom of your list while the list is being updated.):

$(document).ready(function(){
    var $list = $('#list');
    setInterval(function(){
        $list.append('<div id="loader"><i class="fa fa-refresh fa-fw fa-5x fa-spin" aria-hidden="true"></i><br>Waiting...</div>');
        $.ajax({
               type: "GET",
               url: "generate_list.php",
               dataType:"json",
               cache: false,
               success: function(result){
                     $list.html(result.heading);
                     $list.append($('<ul>').append(result.list));
               }
        });
    }, 1000);
});
Comments