Home > Enterprise >  How to render Django template after ajax call
How to render Django template after ajax call

Time:01-11

I am Building a application that renders a group of cards based on options clicked by user, I am using ajax on option click so that cards appear without page reload, but the problem is I cannot render the cards into my page, I am passing calculated values to frontend as django context using return render(request,'base.html',{'context':context})

Ajax:

<script>
function sendData(date){
  $.ajax({
    type : "POST", 
    url: "",
    data: {
      date : date,
      csrfmiddlewaretoken:'{{ csrf_token }}',
      click:'click'
    },

    });

    return false;
}
</script>

view.py:

def datepicker(request):
    if 'click' in request.POST:
        return render(request,'datepicker.html',{'dates':availabe_dates,'time':time})
    
    return render(request,'datepicker.html',{'dates':availabe_dates,'time':['choose a date']})

I have tried giving:

<div >
 {% for t in time %}
    <p>{{t}}</p>
 {% endfor %}
</div>

Only choose a date is shown instead of cards. I am sure that if 'click' in request.POST: is runned as I have tried giving some print statements

I have tried returning jsonResponse and here is its output {time:Array(14)}

Please Help as I am new to Ajax and Django

CodePudding user response:

First Method:

You can return dictionary as response and populate it in jQuery like this:

from django.http import JsonResponse

def datepicker(request):
    if 'click' in request.POST:    
        return JsonResponse({'dates':availabe_dates,'time':time})

and in ajax success:

<script>
function sendData(date){
  $.ajax({
    // rest of the code
    success: function(response){
      $.each(response.time, function (t) {
         $(".card-body").append(t);
      });
    }    
    });

    return false;
}
</script>

Second Method:

You can return html from view and add that in ajax success method like this:

from django.http import JsonResponse
from django.template.loader import render_to_string

def datepicker(request):
    if 'click' in request.POST:
        
        html = render_to_string('datepicker.html', {'dates':availabe_dates,'time':time})
        return JsonResponse(html, safe=False)

and in ajax:

<script>
function sendData(date){
  $.ajax({
    // rest of the code
    success: function(response){
      $(".card-body").html(response);
    }    
    });

    return false;
}
</script>
  •  Tags:  
  • Related