My current project involves incorporating JavaScript functionality to allow for commenting without the need to refresh the page. This works seamlessly when I embed the JavaScript directly into the template. However, when I extract the JavaScript code into a separate file and then load that file within the template, an issue arises: the name of the commenter is not being displayed (although the comment itself appears as expected). Here is the JavaScript snippet used inside the template:
function create_comment(event,div_id,form_id,commentinsert_id) {
event.preventDefault();
var text_id = '#'.concat(div_id,' ','#comment-text')
var slug_id = '#'.concat(div_id,' ','#post_slug')
var appenddiv_id = '#'.concat(div_id)
comment_count ++;
var divcommentinsert_id = 'inserted_comment-'.concat(comment_count.toString())
$.ajax({
url : "create_comment/",
type : "POST",
data : { text : $(text_id).val(), post_slug: $(slug_id).val(),},
success : function(json) {
div.innerHTML = `
<div id = `+divcommentinsert_id+` class="card-footer">
<div class="row">
<div>
<img src="{{user.profile.profile_picture.url}}" alt="" width="40" height="40">
</div>
<div class="col-md-8">
<b style="color:rgb(240, 0, 0);"> {{user.first_name}} {{user.last_name}}</b>
<br>
`+json.text+`
<a onClick="edit_comment('`+json.slug+`','`+divcommentinsert_id+`','`+json.text+`')"><i class="fa fa-edit"></i></a>
<a onClick="delete_comment('`+json.slug+`','`+divcommentinsert_id+`')"><i class="fa fa-trash-o"></i></a>
</div>
</div>
</div>`;
document.getElementById(commentinsert_id).appendChild(div);
document.getElementById(form_id).reset();
},
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>");
console.log(xhr.status + ": " + xhr.responseText);
}
});
};
The line
<b style="color:rgb(240, 0, 0);"> {{user.first_name}} {{user.last_name}}</b>
in the above code is responsible for displaying the commenter's name. While it successfully shows the names when embedded in the template, this functionality breaks when I move the same script to a comments.js file and include it using <script src="{% static 'scripts/comments.js' %}"></script>
. Instead of showing the names, it simply displays {{user.first_name}} {{user.last_name}}. Since I plan to use this JavaScript across multiple pages, I opted to externalize the script into a file for easier maintenance. Any assistance on resolving this issue would be greatly appreciated.