Reputation: 3818
I'm trying to write a simple chat application in Python using Django. Basically I have an empty div which I then use jQuery to append some HTML to from some JSON I get from the server. I've checked the output from the server and the JSON returned is correct so it is not a problem with Django or Python.
This is my JavaScript:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
window.setInterval(function() {
$.getJSON("/chat/messages/" + String({{ channel.id }}) + "/", function(data) {
$("#id_chat_area").html() // clear all HTML in the div before we start printing chat messages
$.each(data, function(key, val) {
$("#id_chat_area").append("<p>" + String(val.username) + ": " + String(val.message) + "</p>")
});
});
}, 5000); // length of time to refresh the function 1000 = 1 second
}, false);
</script>
as you can see I have:
$("#id_chat_area").html()
which I thought would completely clear the div of HTML every time the loop iterates but instead the data returned from the JSON just keeps printing forever without end just appending data on every loop round without clearing the div. Can anyone suggest some code that would clear the div every time that function is executed by the browser so it just shows the data from the last iteration of the loop?
If there is anymore information you need I would be happy to provide it. I'm stumped on this one.
Upvotes: 1
Views: 374
Reputation: 821
change
$("#id_chat_area").html()
to $("#id_chat_area").html("")
might help.
My thought process is that one calls for the html .html() and the other clears it .html("")..
Upvotes: 3
Reputation: 880
This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element.
So to empty your div use:
$("#id_chat_area").empty();
Upvotes: 3