During the AJAX request on the HTML page, additional elements are being added

I've implemented a piece of code that utilizes AJAX calls to refresh an HTML table every 5 seconds.

The approach involves clearing out the content of the table and then appending all data once again every 10 seconds. Here's a snippet of the code:

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

In this code, _appendHere represents the table's id attribute.

Here is the HTML code where the data from my Django view is passed 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 styling is as follows:

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

Additionally, here is the JavaScript part:

var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: {% url 'App1:tempPage' %},  
            data: {'append_increment': append_increment},
        })
        .done(function(response) {
            $('#_appendHere').html('')
            $('#_appendHere').append(response);
            append_increment += 10;
        });
    }, 5000)

A GET request is sent to a 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"),
]

Finally, the views.py file includes the following logic:

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

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

One issue I've encountered is that the input tag (search box) is also being appended, but only once. Despite attempting to enclose it in a separate div, the problem persists. Any assistance would be greatly appreciated. Thank you!

Answer №1

It appears that your AJAX response is including the entire Django response every time, complete with unnecessary line-breaks in the form of <br>, as well as the search form itself.

To streamline this process, you should create a version of the response that only includes the inner HTML required for the table rows.

    <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 %}

By isolating just the rows in the response, you can easily replace them all at once with:

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

Alternatively, if you prefer to work with the full response but only want to target the table, you can achieve this by first loading the response into jQuery and then selecting the table specifically.

var div = document.createElement('div');
div.innerHTML = response;

var html = div.querySelector('#_appendHere').innerHTML;

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interacting with jQuery mouse events on elements below the dragged image

I'm attempting to create a drag-and-drop feature for images using jQuery. While dragging, I generate a thumbnail image that follows the mouse cursor. However, this is causing issues with detecting mouseenter and mouseleave events on the drop target pa ...

Customizing valueAxis dynamically in Amcharts

I am currently utilizing Amcharts to display my data. Within my chart, I have 4 graphs with valueAxes ranging from 0 to 100. Is there a method for me to dynamically change the valueAxes to a range of 0-250 after the chart has been loaded in the view? I ...

Using JQuery to manipulate content with pseudo elements

I'm attempting to modify the arrow displayed in an :after pseudo element. Here's my CSS: legend:after { content: url('/html/img/arrow-fieldset-up.png'); } I am trying to change it with the following JavaScript/jQuery: $('lege ...

What could be causing the failure of code to insert data into the database?

In order to validate my registration form, I have utilized both JavaScript and PHP. While the JavaScript code effectively displays validation error messages, there seems to be an issue with the PHP code. When JavaScript is disabled, the PHP code should s ...

Angular: Modifying the parent scope from a child component

Hey there! So I'm a beginner in this whole programming thing, but I'm currently working on a small application where I can add and update items with details using Ionic, Cordova, and AngularJS. However, I've hit a roadblock with the followin ...

What is the best way to insert a <div class="row"> every 2 items in a Vue.JS template loop?

In my model, I have an array of images' URLs of varying lengths. I want to display 2 images per row on my page, resulting in the following layout: <div class="row"> <div class="col"> <img ... /> </div& ...

Is there a way to deactivate a whole webpage except for a designated "islet"?

One recurring issue I've encountered involves users performing the following actions: Navigate to edit mode on a grid Edit their data Fail to click the save button on the row they are currently editing Mistakenly click the "Next Page" button, assumi ...

Assistance in tackling AJAX and HTML issues

My HTML code is structured in a way that includes a menu with various options. In JavaScript, I iterate through each item and assign a click event listener to them. However, I am facing an issue with determining what data needs to be fetched via AJAX whe ...

Member not found error with JQuery Autocomplete on browsers older than Internet Explorer 10

While constructing a web page with JQuery, I encountered issues with my autocomplete feature when testing it on IE8. The error message reads: SCRIPT3: Member not found. jquery-1.6.4.min.js, line 2 character 29472 After extensive research, I have been u ...

Leveraging JavaScript to unpack references within a intricate object network obtained through SignalR/Json.NET

Utilizing SignalR to send back a complex object hierarchy to my JavaScript client has proven challenging. The JSON structure produced by SignalR/Json.NET contains multiple references to the same object, resulting in a convoluted output like this: { &qu ...

Behavior of jQuery resizable when being used on elements can sometimes

A live demonstration showcasing unusual behavior can be found at: If you attempt to resize the window by grabbing the right border and adjusting it horizontally, the vertical alignment goes awry. This issue persists across all open windows accessed throug ...

Controlling MVC controls dynamically using jQuery

I'm currently working on a table that contains multiple editable fields corresponding to an MVC model object. Each row has a cell with two buttons that toggle between edit and save functions when clicked. I've successfully implemented a mechanism ...

Tips for creating an effective planar reflection using Open Graphics Library (OGL) in conjunction with a perspective camera

I'm attempting to create a mirror-like reflection of a WebGL scene on a plane using ogl, similar to how a mirror would behave. I tried implementing a basic version of the three.js reflector but ended up with a distorted image that doesn't accurat ...

Troubleshooting: Next.js - Issues with encodeURIComponent function when using `/` in getStaticPaths

Reproducible site showcasing the issue: Reproducible code example: https://github.com/saadq/nextjs-encoding-issue Homepage Food page The goal is to dynamically create static pages for different food items based on their titles. This functionality works ...

The issue of an undefined value being returned for a dynamic id in jQuery within a

Struggling to fetch the Post Id in WordPress dynamically using jQuery. Unfortunately, when I try to debug in the console, it keeps returning undefined. Any assistance would be greatly appreciated! Snippet of the code: Displaying the post ID with data-id ...

Having trouble accessing env variables from React Component in Next.js?

I recently set up a Next.js project and included an .env file to store environment variables used in my server.js file. However, I am facing an issue when trying to access these variables from a component. Can anyone provide guidance on how to resolve this ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

Encountered an issue with an unauthorized selection error when using a dynamic dropdown selection list on Drupal 8

For my project, I created a code snippet to implement a dynamic dropdown select list in hook_form_alter. The options for the dropdown are fetched from an external database. function custom_form_alter(&$form, FormStateInterface $form_state, $form_id) { ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Loading Data Dynamically in ASP.NET Using AJAX Spinner

I have incorporated the AjaxToolkit in my asp.net project using C# code. The script manager and update panel are functioning flawlessly, but I am facing difficulty displaying an Ajax loader gif while a request is being processed. Does anyone have any solu ...