Implement AJAX and javascript to generate a pop-up notification using Django's messaging framework

I recently implemented AJAX validation for an input field on my django site by following a tutorial. While it works well, I want to maintain the use of toasts for user alerts, rather than traditional alerts.

$("#id_hub_name").focusout(function (e) {
    e.preventDefault();
   
    var hub_name = $(this).val();
    
    $.ajax({
        type: 'GET',
        url: "{% url 'validate_hubname' %}",
        data: {"hub_name": hub_name},
        success: function (response) {
            if(!response["valid"]){
                // replace alert with toast
                showToast("You cannot create a hub with same hub name", 'error');
                
                var hubName = $("#id_hub_name");
                hubName.val("")
                hubName.focus()
            }
        },
        error: function (response) {
            console.log(response)
        }
    })
})

My goal is to modify the alert functionality in the JS to use toasts instead. In my base.html file, I have already set up a way to dynamically create different types of toasts based on messages received.

{% if messages %}
    <div class="message-container">
        {% for message in messages %}
            {% with message.level as level %}
                {% if level == 40 %}
                    {% include 'includes/toasts/toast_error.html' %}
                {% elif level == 30 %}
                    {% include 'includes/toasts/toast_warning.html' %}
                {% elif level == 25 %}
                    {% include 'includes/toasts/toast_success.html' %}
                {% else %}
                    {% include 'includes/toasts/toast_info.html' %}
                {% endif %}
            {% endwith %}
        {% endfor %}
    </div>
{% endif %}

Any help or suggestions are greatly appreciated.

Answer №1

To display the toast message, simply add the HTML element for it.

Remove the {% if messages %} statement and ensure that the

<div class="message-container">
is always included in your template. Even if there are no messages, this div will still be present. Additionally, make sure to include the toast templates in your JavaScript code so that you can easily append them using JS.

After receiving the ajax response, you can append the toast template like this:

For example:

function show_alert_from_js(alert_type, text) {
        var msg = `<<your template here>>${text}`;  //to render the text message.
        var msg_html = $.parseHTML(msg);
        $('.message-container').append(msg_html);
}

$.ajax({
        type: 'GET',
        ...
        success: function (response) {
            if(!response["valid"]){
                show_alert_from_js("error", "You cannot create a hub with same hub 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

A guide to swapping text in a jQuery DOM component

In order to construct HTML from a jQuery ajax response, I prefer not to nest unsightly strings in javascript and avoid using templating scripts like mustache. Instead, I decided to utilize a template HTML with display: none as shown below: <div id="mes ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

Error message: The attempted import failed because ' is not exported from the module

I am facing an issue with resolving my problem. In a file named lama.d.ts, I have declared a class using the following code: export declare class lama { // code here } After that, I tried to import this class in another file within the same folder ...

How can I create a table using a loop and an onclick function for each <td>?

I have written code to create a table in PHP using a loop. I want to add an onclick function to each cell so that when a particular cell is clicked, the background color changes. However, I am encountering an error. Am I doing something wrong? <head& ...

There was an issue with the event handler: "Encountered an error as 'this.data()' is not recognized as

My HTML list contains links with unique data-… attributes: <ul id="list"> <li><a data-info="link1"> **** </a></li> <li><a data-info="link2">****</a></li> <li><a data-info="link3" ...

Is it possible to convert this to a switch statement?

I am utilizing a code snippet to handle the response from an ajax request, which looks like this: success: function(results) { if(results.locations){ //do stuff here }else if(results.error){ //do stuff here }else if(results.mat ...

The object in Node.js lacks the property 'item' and is therefore undefined

While following The Net Ninja's tutorial on creating a To-do App (https://www.youtube.com/watch?v=IgAH0NqsJso&list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp&index=33), I encountered an issue. While I can delete pre-defined items from the app, I am un ...

JavaScript tutorial: Locate a specific word in a file and display the subsequent word

Seeking assistance with a task: I need to open a locally stored server file, search for a specific word, and then print the next word after finding the specified one. I have managed to write code that successfully opens the file, but it currently prints e ...

Randomly loading Json files in Ionic is a great way to keep your

I have a div using *ngFor which loads values from a JSON file. I want to load values from different JSON files randomly each time the div is loaded. Is there a way to achieve this using Math.random() or any other methods? html file <div class= ...

Guide to setting up a backend system using AJAX, PHP, and MySQL to handle dynamic video sources in conjunction with Google TV Templates

If you're looking to develop web apps for Google TV, particularly those involving video content, the simplest method is to utilize Google TV Templates: https://developers.google.com/tv/web/docs/gtv-templates. The original Google TV Templates included ...

Is there a way to retrieve the value from an input box?

<td class="stockQuantity"> <input class="form-control" id="Cart1" name="qty_req" required="required" type="text" value=""><br> <button type="button" o ...

Handling memory in javascript jquery mobile using phonegap

I have encountered an issue while building a jQuery Mobile + PhoneGap app for iOS. The app functions correctly on a web browser, but when bundled with PhoneGap and tested on a phone, it starts to forget JavaScript functions. For instance, panels that shoul ...

Manipulate a custom member field in a Safecracker form with jQuery, Ajax, and Expression Engine

Currently, I am using jQuery in combination with Expression Engine to send an ajax form. This process involves the Safe Cracker module, which is well-documented on the following page: My form is designed for logged in members to vote. I want to restrict t ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...

Personalize premade designs within a Django app from an external source

I'm currently integrating a third-party app called django-social-share into my Django project. However, I am facing some difficulties in customizing the templates as all my attempts have ended up using the default ones. The default template is locate ...

Turn on and off scrolling of DIV content when hovering over it

How can I create a div that automatically scrolls to the bottom on hover? I tried implementing the code below, but it doesn't work as expected. It jumps to the bottom of the div's height on first hover and transitions smoothly on second hover. . ...

Retrieve the parent ID value using a jQuery click event

I am trying to retrieve the parent div id of a clicked button. The parent div will have a class of .jsgrid. However, my current solution using rootParentId is returning undefined. I believe I may have overlooked something. Can someone help me figure this ...

Encountering a problem while creating a Page Object in webdriver.io - getting the error "setValue is not a function" or "cannot read property 'setValue' of undefined"

While working on a webdriver.io automation project, I encountered an issue with recognizing objects in my page object file (login.po.js) when calling them in the test spec file (test.spec.js). The error message displayed is LoginPage.username.setValue is n ...

Is it time to consider using a Promise in my JavaScript code given its rapid pace of execution?

I want to enhance the user experience of my web app by making elements fade away before being removed. However, I am facing an issue where my code is executing too quickly. I need it to wait for the element to "disappear" before actually removing it. Shoul ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...