Refreshing a Django page without the need to reload the entire page

I am looking to implement a page refresh at specific intervals, such as every 10 seconds, without reloading the page. Currently, I am sending a GET request to an API. While my AJAX code successfully refreshes the page, it reloads all the divs each time causing issues. How can I modify the refresh to only update the specific div without duplicating it?

hmtl;

{% extends 'elements/sidebar.html' %}
{% load static %}
{% block content %}
<!---->
<img src="{% static '/images/techops.png' %}" alt="" class="responsive">
<div class="p text-center bg-light"> 
</div>
<br>
<div class="containerdashcontrol" style="float: top; margin-bottom: 2%;">
  <div class="dashbaslik" style="text-align: center;"> <span style="font-size: 30px; color: white;">DASHBOARD CHECK</span></div>
  <form class="form-horizontal" action="dashcontrol" method="POST">
    {% csrf_token %}
    {% load humanize %}
                   <!---->   
  </form> 
  </div>
  <!-- Modal -->
  <section class="pricing-section">
    <div class="container">
        <div class="row justify-content-md-center">
            <div class="col-xl-5 col-lg-6 col-md-8">
            </div>
        </div>
        <!-- Pricing Table starts -->
        <div id="testdiv" class="row">
      <div class="col-md-4">
          {%if testtt > 1000 %}<div class="dashcontrol2 featured">{%else%}<div class="dashcontrol featured">{%endif%}
          <h4>{%if testtt > 1000 %}<span style="color: red;">XX</span><box-icon type='solid' name='badge' color="red"></box-icon>{%else%}<span style="color: green;">XX</span><box-icon type='solid' name='badge-check' color="green"></box-icon>{%endif%} </box-icon></h4>
          <h4>{{testtt|intcomma}}</h4>
         <a target="_blank" href="XX"><h6>KIBANA</h6></a>
        </ul>
       </div>
      </div>
</section>
            </div>
    <script>
        setInterval(function() { 
            $.get("/dashcontrol", function(data, status){ 
                $("#testdiv").hide(); 
                $("#testdiv").html(data); 
            });  
        }, 5000);
    </script>
    {% endblock content %}
    {% block scripts %}
  
    {% endblock scripts %}

url.py;

url(r'^dashcontrol$', views.dashcontrol, name='dashcontrol'),

ajax;

<script>
        setInterval(function() { 
            $.get("/dashcontrol", function(data, status){ 
                $("body").html(data); 
            });  
        }, 15000);
    </script>

view;

def dashcontrol(request):
        url = "http://XX/XX*/_search"
        headers = {'Content-type': 'application/json'}
        params = {XX}
        print('OK')
        response = requests.get(url=url, json=params, headers=headers)
        data = response.json()
        testtt = data['hits']['total']
        print(data['hits']['total'])
        print('OK')
        return render(request, 'dashcontrol.html', {'testtt ':testtt }

Answer №1

Here is a potential solution:
The default duration is set to 400ms, which may go unnoticed by the user.
Create a new URL

url(r'^dashcontrol$', views.dashcontrol, name='dashcontrol'),
url(r'^updatadashcontrol$', views.updatedashcontrol, name='updatedashcontrol'),

JS

<script>
          
    setInterval(function() { 
      $.get("{% url 'updatedashcontrol' %}", function(data, status){ 
        $("#testdiv").empty(); //Hide the page
        $("#testdiv").append(data); // And after you hide that data, append it
    });  
}, 15000);
    </script>

views.py

def dashcontrol(request):
        url = "http://XX/XX*/_search"
        headers = {'Content-type': 'application/json'}
        params = {XX}
        print('OK')
        response = requests.get(url=url, json=params, headers=headers)
        data = response.json()
        testtt = data['hits']['total']
        print(data['hits']['total'])
        print('OK')
        return render(request, 'dashcontrol.html', {'testtt ':testtt }

def updatedashcontrol(request):
        url = "http://XX/XX*/_search"
        headers = {'Content-type': 'application/json'}
        params = {XX}
        print('OK')
        response = requests.get(url=url, json=params, headers=headers)
        data = response.json()
        testtt = data['hits']['total']
        print(data['hits']['total'])
        print('OK')
        return render(request, 'partialdashcontrol.html', {'testtt ':testtt }

partialdashcontrol.html(just this do not add body or html)

<div class="col-md-4">
          {%if testtt > 1000 %}<div class="dashcontrol2 featured">{%else%}<div class="dashcontrol featured">{%endif%}
          <h4>{%if testtt > 1000 %}<span style="color: red;">XX</span><box-icon type='solid' name='badge' color="red"></box-icon>{%else%}<span style="color: green;">XX</span><box-icon type='solid' name='badge-check' 

    color="green"></box-icon>{%endif%} </box-icon></h4>
              <h4>{{testtt|intcomma}}</h4>
             <a target="_blank" href="XX"><h6>KIBANA</h6></a>
            </ul>
           </div>

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

Updating the information displayed in one section by selecting a button on the Google Maps infowindow located in a separate section

My webpage is divided into multiple divisions. One division contains a map using the Google Maps API with markers. When I click on a marker, an info window opens up. Now, I am attempting to place a button inside that info window which, when clicked, will ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...

Tips for making a multiselect dropdown menu using bootstrap

I am working on a JavaScript application that parses data and displays it to users in a table generated by JavaScript. I am looking for a simple way to allow users to choose which fields to display in the table using a dropdown list or something similar. I ...

Utilize React to reduce, replace, and encapsulate content within a span element

I have a Map that receives JSON data and generates a list item for each value. Then, I modify specific parts of the strings with state values. const content = { "content": [ { "text" : "#number# Tips to Get #goal#" ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Identifying when a page-loading or reloading event has been canceled

When the Cancel button is pressed during page load/reload, the content of the page loads partially. Is there a more effective way to address this issue rather than displaying incomplete content? For instance, consider showing a message such as "Page load ...

What measures does Django take to sanitize text input in its forms and prevent vulnerabilities like SQL injection and XSS attacks?

Is there a protection in place for preventing SQL injection attacks when user input is passed into the database through Django forms? How does Django handle raw text input sanitization to ensure this security measure? ...

Optimal methods for sending Redux state to components

Currently, I am collaborating on a React + Redux project alongside other developers, and we are at an impasse regarding the best practice for passing state and actions throughout our components. My strategy involves creating a 'container' or &ap ...

Trouble encountered with updating the Input value upon pressing the enter key

In my ReactJS-based application, I am working on a component that includes a Material Input element. Users can enter words and when they press the enter key, those words are displayed as chips within the same input field. The issue I'm encountering i ...

There seems to be an issue with the function code error when calling it within the

When I attempt to run my code in this way, I encounter a compile time error stating that the expression statement is not an assignment or call... (within the else statement). What am I missing here to get it to work? I've made numerous attempts to ad ...

Exploring ways to query a mapped array in React Native

Struggling to search a mapped list in react native? While using a Flatlist would be easier, this task is currently causing me major frustration. If anyone has any insights or solutions, please share them! Here's a snippet of the code: import React ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

Using Selenium and Java to retrieve population data from en.wikipedia.org for countries

I am attempting to retrieve the population data from a specific element. I have attempted to use the parent method, but encountered an error. My goal is to extract the population information for China from the table on this page: https://en.wikipedia.org/ ...

Utilizing Vue.js to dynamically update input fields based on other field values

I'm a beginner with Vue.js and Vuetify.js, and I am encountering some difficulties with the following: <v-select v-model="car.type" :items="types" label="Type" ></v-select> <div v-if="car.type === 'fiat'"> < ...

Achieving ajax loading with URL change without triggering a page redirection

When browsing on Facebook, you may have noticed that when moving from one page to another, the entire page does not reload or redirect; instead, the URL changes as you navigate. This is especially noticeable when chat windows are open, as they stay in plac ...

How come the likes are not being refreshed when the button is clicked in my mongoose schema?

I am currently working on an express app using nodejs and mongoose. My main goal is to implement a JavaScript function that can update the number of likes on a post in a database directly from my ejs file. However, I have encountered troubles with this tas ...

Is there a way to have two SVG files displayed on a single HTML page at the same time

Currently, I am facing an issue with my graphs. I have a line graph and a boxplot, but the boxplot is appearing below the line graph when I want it to be next to it. Any suggestions on how I can achieve this layout? Thank you! I attempted to use 2 differe ...

Learn how to render a dynamic checkbox that is connected with AJAX and PHP for seamless functionality

I need to showcase a dynamic checkbox that can be bound using ajax and php. Here is my code: <?php include 'dbconnect.php'; $result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' "); while($city_row=mysqli_fe ...

I successfully set up ApacheOpenmeetings on a dedicated server. Now, I am wondering how to connect to its REST APIs from a different application

Encountering the following error when making a request from localhost:- XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed acces ...