Buky Buky -4 years ago 128
Ajax Question

Django render on the same template

I try to create a pagination, so i use a some lines of JS to send data, i catch it correctly (and can print it in the console) and i see they are different but my render never change.

Console.log:

[15/Mar/2017 14:30:09] "POST /index/ HTTP/1.1" 200 15320
[POST] 2
[15/Mar/2017 14:30:10] "POST /index/ HTTP/1.1" 200 9003
[POST] 3
[15/Mar/2017 14:30:10] "POST /index/ HTTP/1.1" 200 9003
[POST] 4
[15/Mar/2017 14:30:16] "POST /index/ HTTP/1.1" 200 9003
[POST] 1


Template.html:

<p> THIS IS THE PAGE {{ page }} </p>

<div class="col-xs-12 center">
<ul class="pagination" >
<li><a href="#" value={{ page|add:"-1" }}>&laquo;</a></li>
<li><a href="#" value=0>1</a></li>
<li><a href="#" value=1>2</a></li>
<li><a href="#" value=2>3</a></li>
<li><a href="#" value=3>4</a></li>
<li><a href="#" value=4>5</a></li>
<li><a href="#" value={{ page|add:"1" }}>&raquo;</a></li>
</ul>
</div>

<script language="javascript">
$('ul.pagination li a').on('click', function(e){
e.preventDefault();
$.ajax({
url: '/index/',
type: 'POST',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {'page': $(this).attr('value')},
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
processData: true,
});
})
</script>


Views.py:

def index(request):
print("[POST]",request.POST.get('page'))
page = int(request.POST.get('page', 0))
return render(request, "site/index.html",
{'page': page})


So I think if i'm on
/index/
i can't do a new render of index with new variable (and new render with this variable as well) ?

Do you have an idea when i can do that ?

EDIT: i add console log prove i catch the value of
page
with JS.

Answer Source

To print the page already format in HTML by the Django rendering engine, use the function in ajax to to overwrite a the current page : $("html").html(response); so just adjust the javascript part.

<script language="javascript">
    $('ul.pagination li a').on('click', function(e){
        e.preventDefault();
        $.ajax({
            url: '/index/',
            type: 'POST',
            headers: {'X-CSRFToken': '{{ csrf_token }}'},
            data: {'page': $(this).attr('value')},
            'success': function(response)
            {
                $("body").html(response);
            }      
        });
   })
</script>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download