In one of my articles, I have enabled a commenting feature. When a user clicks the reply button on a submitted comment, an Ajax request is sent to fetch HTML content from a file. This content is then added as a new element to the DOM, containing the reply form.
The JavaScript code I'm using for this functionality is:
function handle_ajax_request(event) {
if (request.readyState === 4) {
if (request.status === 200 || request.status === 304) {
console.log("Successfully received AJAX response from the server.");
parentElement = document.getElementById("reply_comment");
reply_form_element = document.createElement("div");
reply_form_element.id = "reply_comment_form";
parentElement.appendChild(reply_form_element);
reply_form_element.innerHTML = request.responseText;
} else {
console.log("Error: Failed to retrieve AJAX response!");
}
}
}
function get_reply_form(event) {
event.preventDefault();
reply = document.getElementById("reply_comment");
request = new XMLHttpRequest();
if (!request) {
console.log("Error: Unable to create AJAX request.")
}
console.log("Ajax request created, checking state.");
request.onreadystatechange = handle_ajax_request;
request.open("GET", "http://localhost:8000/static/html/experience/comment_reply_form.html", true);
request.send(null)
}
The file fetched through the Ajax request contains Django template syntax, which looks like this:
{% load comments %}
{% get_comment_form for article_details as form %}
<form action="{% comment_form_target %}" method="post">{% csrf_token %}
{{ form.object_pk }}
{{ form.content_type }}
{{ form.timestamp }}
{{ form.security_hash }}
{% if node.id %}
<div class="form-group">
<input type="hidden" class="form-control" name="parent" id="parent_id" value="{{ node.id }}" />
</div>
{% endif %}
{{ form.comment }}
<div class="col-md-4">
<div class="form-group">
<input type="hidden" class="form-control" name="next" value="/article/display/{{ article_details.id }}" />
<input type="submit" class="form-control" value="Reply">
</div>
</div>
</form>
When adding this HTML to a div on the page, the Django syntax is not getting interpreted correctly by Django itself. Instead, it appears literally in the browser:
Posted by an anonymous user 4 days, 20 hours ago
test
Reply
{% get_comment_form for article_details as form %}
{% csrf_token %} {{ form.object_pk }} {{ form.content_type }} {{ form.timestamp }} {{ form.security_hash }} {% if node.id %}
{% endif %} {{ form.comment }}
Some anomalies are present in the HTML where quotes and extra characters interfere with the Django syntax interpretation. Additionally, it seems that every opening curly brace '{' is preceded by a quote symbol. This issue arises despite not utilizing jQuery but focusing on learning plain vanilla JavaScript.