[Fixed]-Using Ajax in Django to display time of day every second

1๐Ÿ‘

EDIT:

You also need jquery. Add <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> before your other script block in the html.

See documentation on setTimeout and setInterval: http://www.w3schools.com/jsref/met_win_settimeout.asp
http://www.w3schools.com/jsref/met_win_setinterval.asp

Change the javascript to this:

function refresh() {
    $.ajax({
        url: '{% url monitor-test %}',
        success: function(data) {
            $('#test').html(data);
        }
    });
}

$(function(){
    setInterval(refresh, 1000);
});

or maybe this would be better:

function refresh() {
    $.ajax({
        url: '{% url monitor-test %}',
        success: function(data) {
            $('#test').html(data);
            setTimeout(refresh, 1000);
        }
    });
}

$(function(){
    refresh();
});
๐Ÿ‘คuser1132959

0๐Ÿ‘

Iโ€™m using this, is a default tag in django.

    <ul class="sidebar-stats">
        <li class="margin left right">
            <h5>{% now "j F Y H:i" %}</h5>
        </li>
    </ul>
๐Ÿ‘คPaulo Pessoa

0๐Ÿ‘

user1132959 was spot on! I needed to add:

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

I had some issues with the number of times per cycle the page was being updated. I think this may have been because of cache, but I am not sure.
Here is what I have now that seems to be working.

refreshTime.js:

function refreshTime() {
  $.ajax({
    url: '{% url time %}',
    success: function (data) {
      console.log("success function called");
      $('#test').html(data);
    }
  });
}


$( document ).ready(function () {
  console.log("setting interval");
      setTimeout(refreshTime,1000);
});

time.html:

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/static/garageMonitor/scripts/refreshTime.js"></script>

<table id="test">
  <tbody>
    <tr>
      {% include "testing.html" %}
    </tr>
  </tbody>
</table>

urls.py:

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
  url('time', time, name="time"),
)

views.py:

def time(request):
  now = strftime("%H:%M:%S", gmtime())

  time_dict = {"Time":now}
  return render_to_response('time.html', {'time': time_dict})

I really hope this helps someone else get to the end of their rainbow faster than I did.

thanks to all who helped me!

๐Ÿ‘คjordanthompson

0๐Ÿ‘

You donโ€™t need Django to do this โ€“ just HTML and JavaScript.

In your time.html file, use the following to display current time (updating every second):

<span id="time">

<script>
    function GetTime(){
    var dt = new Date();
    document.getElementByID("datetime").innerHTML = dt.toLocaleTimeString();
    }
    setInterval(GetTime,1000);
</script>
๐Ÿ‘คEd Kloczko

Leave a comment