2

Trying to build a web application for the first time using Django. The table UI from the below script is rendering the data for the first time. But the Ajax call doesn't seem to call the get_more_tables in views.py and refresh the table data.

I have already looked at but didn't help my case Reload table data in Django without refreshing the page

home.html


{% extends "templates_dashboard/base.html" %}
{% block content %}

<head>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script> <!-- ADD THE CLOSING TAG HERE TOO! -->
  </head>

        <td class="more-padding-on-right">CURRENT RESPONSE TIME OF WEBSITES</td>
        <table id="_response_time" class="table table-striped table-condensed">
          <tr>
            <th>Website</th>
            <th>Current Response Time(ms)</th>
          </tr>
          {% for posts in posts2 %}

             <td>{{ posts.website }}</td>
             <td>{{ posts.response_time}}</td>
          </tr>
          {% endfor %}
        </table>




<script>  // <-- ADD THIS!
$(document).ready(function () {
    var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: "{% url 'get_more_tables' %}",
            data: {'append_increment': append_increment}
        })
        .done(function(response) {
            $('#_response_time').append(response);
            append_increment += 10;
        });
    }, 10000)
  })
</script>
{% endblock content %}

get_more_tables.html

{% load static %}
{% for post in posts %}
<tr>
   <td>{{ post.website}}</td>
   <td>{{ post.response_time }}</td>
</tr>
{% endfor %}

urls.py

urlpatterns = [
    path('', views.home , name='dashboard-home'),
    path('about/',views.about, name='dashboard-about'),
    path('get_more_tables', views.get_more_tables , name='get_more_tables'),
]

views.py

def get_more_tables(request):
    logger.info('************************************************** Refreshing Table Content')
    increment = int(request.GET['append_increment'])
    increment_to = increment + 10
    my_response = responseTime()
    return render(request, 'templates_dashboard/get_more_tables.html', {'posts': my_response[increment:increment_to]})

I'm expecting the table data for website and Response time to refresh every 10 seconds by printing the logger message in get_more_tables. I cannot see the table data getting refreshed or the logger message in the logs which made me think that the get_more_tables function is not invoked. Can someone help me understand why the get_more_tables function in views.py is not called?

pvr
  • 31
  • 5
  • are you receiving the request in views.py? if not i think here is problem url: '{% url 'get_more_tables' %}' in ajax – HERAwais Apr 20 '19 at 04:13
  • @HERAwais Sorry, How can I verify that? I don't see the logger message printing in the logs. – pvr Apr 20 '19 at 04:16
  • The answer you linked to was my original post! Can you elaborate on what `responseTime()` is? It may be what is causing your issue. Also, add a `/` at the end of your url path – Hybrid Apr 20 '19 at 04:18
  • In your urls.py add **/** at the end which is path('get_more_tables/', views.get_more_tables , name='get_more_tables'), and in ajax request url: '/get_more_tables/', – HERAwais Apr 20 '19 at 04:20

1 Answers1

0

The link you provided was from my old answer! What a small world.

In any case, your issue is on this line:

url: '{% url 'get_more_tables' %}',

The single quotes cancel each other out - you should make it look like this:

url: "{% url 'get_more_tables' %}",

EDIT

Also, it looks like you are missing an opening <script> tag before your JS, and a closing </script> tag after your jQuery import:

<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script> <!-- ADD THE CLOSING TAG HERE TOO! -->

<script>  // <-- ADD THIS!
$(document).ready(function () {
    var append_increment = 0;
    setInterval(function() {
        $.ajax({
            type: "GET",
            url: "{% url 'get_more_tables' %}",
            data: {'append_increment': append_increment}
        })
        .done(function(response) {
            $('#_response_time').append(response);
            append_increment += 10;
        });
    }, 10000)
})
</script>
Hybrid
  • 5,656
  • 2
  • 18
  • 42
  • I have updated the url with double quotes and added a / in the urls.py ```path('get_more_tables/', views.get_more_tables , name='get_more_tables'),```. It doesn't print the log message still. I think get_more_tables in views.py itself is not getting called. – pvr Apr 20 '19 at 04:36
  • Is your logger set up? Try `print("Refreshing tables")` above your `logger.info(...)` code and let me know if it prints anything out to your terminal – Hybrid Apr 20 '19 at 04:37
  • My logger is set up and looks good. ```views.home``` has a logger message and I can see it printing everytime I restart the server and refresh the web page. – pvr Apr 20 '19 at 04:41
  • Try adding `console.log("Requesting...")` right above `$.ajax()` and let me know if the code is even being executed in your browser's inspector console – Hybrid Apr 20 '19 at 04:45
  • I added ```setInterval(function() { console.log("Requesting...") $.ajax({``` and restarted the server. From chrome inspect element, went to Console -> selected All Levels in log levels. I don't see log getting printed. – pvr Apr 20 '19 at 04:48
  • Check my answer's edit - I'm pretty sure you forgot to add your beginning – Hybrid Apr 20 '19 at 04:51
  • I still don't see the console log message :( – pvr Apr 20 '19 at 04:59
  • Should I remove ``` – pvr Apr 20 '19 at 05:00
  • That should be it! Add a closing `` tag directly after that jQuery import tag, otherwise, it will think all your JS code is a part of that import. You can see my edited answer for the full code, let me know if that works. – Hybrid Apr 20 '19 at 05:02
  • That is causing an error message in the inspector console logs ```ncaught TypeError: $.ajax is not a function``` This could be because of https://stackoverflow.com/questions/44212202/my-javascript-is-returning-this-error-ajax-is-not-a-function – pvr Apr 20 '19 at 05:05
  • Look at my edited answer - don't remove the jquery import - you just need to add a `` closing tag after it – Hybrid Apr 20 '19 at 05:06
  • I replaced my code with your code as it is. Every 10 seconds I receive ```Uncaught TypeError: $.ajax is not a function``` in the inspector console log. – pvr Apr 20 '19 at 05:12
  • I have updated my Question with the updated home.html from your above suggestions. – pvr Apr 20 '19 at 05:16
  • Try moving `` to the bottom of your `...` code. It might not be loading before your code executes. Also, add the `$(document).ready()` code I added in my edit. – Hybrid Apr 20 '19 at 05:22
  • Updated my question with your suggestion to move to and added the ```$(document).ready()``` as well. Still running into ```Uncaught TypeError: $.ajax is not a function``` error in the inspector – pvr Apr 20 '19 at 05:33
  • Ha you need to put the jquery include in the head section inside of `base.html` (or whatever your root template is). Putting it in home.html wont do anything – Hybrid Apr 20 '19 at 05:36
  • Ahh.. Finally, it is responding. It is adding the records to the table instead of updating the existing values. – pvr Apr 20 '19 at 05:45
  • The current code is adding 2 records every 10 seconds to the table data. How do I update the existing 2 records with the new values instead of adding 2 new records every 10 seconds? ```data: {'append_increment': append_increment}``` Is this the reason? – pvr Apr 20 '19 at 05:55
  • You would need to add the IDs of the posts you want to update into the AJAX get request (instead of `append_increment`), filter them in the view (`Model.objects.filter()`), and then use `.html()` instead of `.append()` to reinsert it into the table – Hybrid Apr 20 '19 at 06:02
  • 1
    Thank you so much! Though my table borders and colors are not retained. I can see the data getting refreshed! – pvr Apr 20 '19 at 06:16