Django Ajax toastr not display when success

47 Views Asked by At

I encounter a problem with ajax toastr, i'm using bootstrap 5 also so that might be cause style problem.

My Ajax:

{% load humanize %}
{% load static %}
<link rel="stylesheet" href="{% static 'style.css' %}">
<link href="toastr.css" rel="stylesheet"/>
{% block extra_js %}
<script src="toastr.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" 
      integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" 
        crossorigin="anonymous"></script>
<script type="text/javascript"> 
    let csrftoken = '{{ csrf_token }}'
    $(document).on('submit','#add-to-favourite',function(e){ 
        e.preventDefault(); 
        $.ajax({
        type: $(this).attr('method'),
        headers:{'X-CSRFToken':csrftoken},
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function (response) {
            alert("Succes");
            toastr.options.closeButton = true;
            toastr.success('Added to Favourite');
        }
    })
    });  
</script>
{% endblock extra_js %}

the alert message display ok so ajax function return success.

1

There are 1 best solutions below

1
On

The importation of the lib toastr have to be done after the importation of Jquery as Jquery is a dependance of toastr.

Just put

<script src="toastr.js"></script>

after

<script src="https://code.jquery.com/jquery-3.5.1.js" 
      integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" 
        crossorigin="anonymous"></script>

like that :

{% load humanize %}
{% load static %}
<link rel="stylesheet" href="{% static 'style.css' %}">
<link href="toastr.css" rel="stylesheet"/>
{% block extra_js %}
<script src="https://code.jquery.com/jquery-3.5.1.js" 
      integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" 
        crossorigin="anonymous"></script>
<script src="toastr.js"></script>
<script type="text/javascript"> 
    let csrftoken = '{{ csrf_token }}'
    $(document).on('submit','#add-to-favourite',function(e){ 
        e.preventDefault(); 
        $.ajax({
        type: $(this).attr('method'),
        headers:{'X-CSRFToken':csrftoken},
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function (response) {
            alert("Succes");
            toastr.options.closeButton = true;
            toastr.success('Added to Favourite');
        }
    })
    });  
</script>
{% endblock extra_js %}