Home > Net >  Not able to retrieve variable in template in Django ajax call
Not able to retrieve variable in template in Django ajax call

Time:12-12

I am trying retrieve counter value passed from view in the html template .It is coming as None, however in the view print and in ajax success log value it is coming correct.

JS ajax func

           $(".pos").click(function(){
            counter=counter 1;
            $(".add").html('add counter ' counter);
            $.ajax(
                { url :'page',
                  type :'get' ,
                 
                  data:{
                    quantity: counter
                   },
                    
                success:function(response){
                  console.log(response);
                }

                   
                   

                }
            );

My view

def page(request):
    counter=request.GET.get('quantity')
    print(counter) ## this is printing fine
    return render(request,'page.html',{'counter':counter})

html template

<body>
    {{counter}}
    <button  name="neg-btn">-</button>
    <button  name="add-btn" >add to box</button>
    <button  id="test" name="pos-btn"> </button>
</body>

getting this counter as None

CodePudding user response:

Usually you would have two views, one to render the template and another for your ajax request. This helps to keep your code more organized and have functions do exactly one task as most of the its described in its naming.

One important thing that is happening in your view, is that you are returning the HTML generated by the render API and not the counter value. Of course, there are many ways to do this correctly, but here is one possible solution:

page.html

{% extends 'base.html'%}

{% block content %}
<body>
    <div id="counter">
        {{counter}}
    </div>
    
    <button  id="neg" name="neg-btn">-</button>
    <button  id="add" name="add-btn" >add to box</button>
    <button  id="pos" name="pos-btn"> </button>
</body>
{% endblock content %}

{% block script %}
<script>
    let counter = parseInt("{{counter}}");
    let page_url = "{% url 'core:page' %}";
    console.log(page_url)
    $( "#pos" ).click(function() {
        counter  = 1;
        $( "#counter" ).replaceWith(`<div id="counter">${counter}</div>`);
    });
    $( "#neg" ).click(function() {
        counter -= 1;
        $( "#counter" ).replaceWith(`<div id="counter">${counter}</div>`);
    });
    $( "#add" ).click(function() {
        $.ajax({ 
                    url :page_url,
                    type :'post' ,
                    data:
                    {
                        counter: counter,
                        csrfmiddlewaretoken: '{{ csrf_token }}',
                    },                    
                    success:function(response){
                    console.log(response);
                    }
                });
    });
</script>
{% endblock script %}

views.py

from django.http import JsonResponse

def page(request):
    counter = 0
    if request.method == 'POST':
        counter = int(request.POST.get('counter'))
        print(counter)
        return JsonResponse({'counter': counter})
    
    return render(request,'page.html',{'counter':counter})
  • Related