Django: Comparing the benefits of embedding JavaScript in templates versus loading it externally

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'>&times;</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.

Answer №1

{{ dictionary.key }} is a key aspect in utilizing variables within the django template engine.

It's important to note that a static javascript file does not function as a template and does not undergo processing by the django template engine.

To access the necessary values in your HTML, utilize the template engine and then access them from JavaScript.

Key concepts to keep in mind:

  • Create a JavaScript variable (e.g.

    <script>var user_full_name = "{{ user.user_name }} {{ user.last_name }}"</script>
    ) and use user_full_name within the ajax success callback.

  • Embed the values within an HTML element (e.g.

    <input type="hidden" id="user_name" value="{{ user.user_name }}">
    ) and retrieve it using JS/jQuery with $("#user_name").val().

edit: included the previously omitted closing double quote in the declaration of user_full_name.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Ajax for Dynamically Filling a Dropdown Menu

My journey into the world of Ajax has led me to a state of confusion and frustration. The task at hand is to populate the first box with customer data from the database, then use the customerID to retrieve all vehicleID's using the select.php script. ...

Utilizing ng-repeat to iterate over a nested array

I need help figuring out how to properly loop through a JSON array and its ingredients/directions array using ng-repeat. The current method I have attempted is not working as expected. Any suggestions or advice would be greatly appreciated! Thank you. Con ...

Issue with Sheetjs: Date format is not recognized when adding JSON data to a

I am struggling to export JSON data to Excel while maintaining the correct date format of 2020-07-30 07:31:45. Despite trying suggestions from a helpful post on sheetjs, I still couldn't get it right. Here is an example of the JSON data: { "so ...

Creating a mesmerizing glass effect in Three.js using a PNG image mask on a video texture

The other day, I revisited activetheory.net and was captivated by the beautiful glass effect on the Homescreen logo border. I tried to replicate it by examining the minified code and discovered they were using a PNG as a mask. I successfully loaded a PNG ...

Pressing the Button Increases the Counter, However the Counter Resets After

My goal is to create a basic counter with increment and reset buttons. When I click on the increment button, the counter properly goes from 0 to 1 (I can confirm this by checking the console log in Chrome). The issue arises when, after incrementing, the c ...

Allow all images on the webpage to be easily dragged and dropped into a designated upload section

I am in the process of developing a browser extension that allows users to save images from web pages into their favorites, similar to Pinterest. The functionality involves clicking on the extension icon which adds a special field to the HTML where users c ...

A step-by-step guide on using Javascript to transform images into text

Hey there! I'm looking for some help to convert an image into text. The idea is that when someone uploads an image and hits the "Submit" button, the text from the image should display in a textarea below. However, the code I've been working on do ...

Sending a POST Request between two websites using JavaScript

I am facing an issue where I need to send a POST request from an application on SERVER1 to another application running on SERVER2. SERVER1: <form name="submitForm" method="POST" action="http://SERVER2:4120/download_item/&qu ...

The button is not activating the callback function when clicked. It is unclear why this is happening as no errors are being displayed in the console

Utilizing an event listener on the button element, the user is prompted to select a language first. Upon selection, the button in question is presented to them. Clicking on this button triggers a callback function that allows the user to begin the quiz. Ev ...

Issue encountered: ImportError when attempting to utilize google-auth

I integrated google-auth for Firebase authentication in my GAE project successfully. Everything runs smoothly with dev_appserver.py and Google App Engine deployment, but I encounter ImportError exceptions when attempting to use Django's manage.py scr ...

The Jquery slider panel seems to be stuck open even after I switched its CSS orientation from right to left

I am following up on a previous question, which can be found here. After fixing the jQuery code, I decided to change the panel slider to open from the left side instead of the right. I modified the class from "cd-panel from-right" to "cd-panel from-left". ...

Attempting to execute a PHP script through a JavaScript if statement

I have a form that requires validation with JavaScript. In one of the if statements, after all other conditions have been validated, I want to execute my PHP script that updates an SQL database with one of the passwords. Here is the final validation code: ...

Is it possible to utilize a route path in a JavaScript AJAX request?

So I have a situation with an ajax call that is currently functioning in a .js file, utilizing: ... update: function(){ $.ajax({ url: '/groups/order_links', ... However, my preference would be to use the route path instead. To achieve ...

Unleashing the Power of Dynamic JSON Data Access

I am facing an issue with my React Child component. Here is the code snippet: const SingleProject =(props)=>{ let data = projectData.VARIABLE_FROM_PROPS.projectDetails; let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar; useEffe ...

Is it not possible to make updates while the state is already in transition?

this.state = { filterData: [{ attribute: '-1', filter: '-1', value: '' }], } _createFilterUI(dataSourceColumns) { if (this.state.dataSourceIndex == -1) return <div > Kindly first select Data Sourc ...

Adjusting the size of content tags depending on their popularity

Currently, I am working on setting up a basic tagging system by following the database structure provided in this Stack Overflow post. My goal is to create a single page that showcases all the tags, with each tag being visually scaled based on its popular ...

the three.js code runs smoothly on JSfiddle, but it does not seem to be working properly

Check out this basic three.js code snippet for generating custom geometry http://jsfiddle.net/67Lgzjpb/. After attempting to run this code directly in my browser (not via JSFiddle), an error message pops up: TypeError: geom.computeCentroids is not a funct ...

Shopping cart has encountered an issue with storing the data correctly

While I've managed to successfully integrate another service, the challenge now lies in implementing the logic for correctly generating cart items. My goal is to increment the quantity of items in the cart by one with each function call, but it seems ...

Incorporating JS objects into HTML: A comprehensive guide

Here is a snippet of code from my JavaScript file: var formStr = "<h5>How many books?:</h5><input type='number' id='bookinput' value='' /><input type='button' value='submit' onclick=& ...

JavaScript Firebase: Service worker malfunctioning during navigation

I'm currently developing a website that relies on firebase messaging. To make this happen, a specialized service worker for firebase has been integrated into the site. This website functions as a webchat platform where messages are synchronized and s ...