'Extra elements getting appended during AJAX call on html page

I have a piece of code that refreshes an HTML table every 5 seconds using AJAX calls

I am basically emptying out the HTML table and then appending all of its data again every 10 seconds to achieve this

Something like this -

$('#_appendHere').html('')
$('#_appendHere').append(response);

where _appendHere is the id attribute of the table

This is my HTML code - (the data is being passed from my Django view to this page)

<body>
    <div>
        <div>
        <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
        </div>
    </div>

    <br>
    <br>
    <br>
    <br>

    <table id="_appendHere" class="table table-striped table-condensed">
        <tr>
          <th>Username</th>
          <th>Email</th>
          <th>Gender</th>
        </tr>
        {% for item in info_data %}
          <tr>
            <td>{{item.username}}</td>
            <td>{{item.email}}</td>
            <td>{{item.gender}}</td>
          </tr>
        {% endfor %}
      </table>

</body>

The CSS -

<style>
    table, td, th {  
        border: 1px solid #ddd;
        text-align: left;
    }
    
    table {
        border-collapse: collapse;
        width: 100%;
    }
    
    th, td {
        padding: 15px;
    }
</style>

And this is the javascript section -

var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: {% url 'App1:tempPage' %},  // URL to your view that serves new info
            data: {'append_increment': append_increment},
        })
        .done(function(response) {
            $('#_appendHere').html('')
            $('#_appendHere').append(response);
            append_increment += 10;
        });
    }, 5000)

The GET request is being made to this URL in a Django view which renders the same page -

from django.contrib import admin
from django.urls import path,include
from App1 import views
app_name = 'App1'

urlpatterns = [
    path('temp/', views.tempPage,name="tempPage"),
]

The views.py file -

from django.shortcuts import render
from App1.models import Info

# Create your views here.
def tempPage(request):
 
    info_data = Info.objects.all()
    context={"info_data":info_data}
    return render(request, 'App1/temp1.html', context)

For some reason, this code appends the input tag (the search box) as well.. but does it only once

enter image description here

And I am not sure why this is happening

I tried putting the input tag in a different div but that also does the same thing

Any help would be highly appreciated!! Thanks!!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source