Krash
Krash

Reputation: 2287

Django template not re-rendering on successful AJAX get request

I have written a very simple ajax code which makes a get request, and it expects django template values as response. So when I try to execute this ajax code, in chrome under network, I can see that the get request was successful and in the preview section under network, I can see the template values that I had expected but the webpage remains same, doesn't get rendered again.

My view:

def test(request,id=1):
    return render(request,'test.html',{'num':id,'next':9})

My template and ajax code:

<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<p>{{num}}</p>
<button onclick='test({{next}})'>Test</button>

<script>
function test(next){
    $.ajax({
        url:'/test/'+next,
        type: 'GET',
        success: function(){
            console.log('done');
        }
    });
}
</script>

Please check this sample image of my problem when I started on '/test/66' , made a click on the button, got the required response, still no change. Sample Request

Upvotes: 0

Views: 931

Answers (1)

WilomGfx
WilomGfx

Reputation: 2013

You're mixing server side rendering (DTL) and client side (javascript). Once django as rendered the template, you're javascript has no access to server side variable as {{ text }}.

You will have to do :

Template before SSR

<div id="content">
  <p>{{num}}</p>
  <button onclick='test({{next}})'>Test</button>
</div>

<script>
    function test(next){
        $.ajax({
            url:'/test/'+next,
            type: 'GET',
            success: function(data){
                document.querySelector('#content p').innerHTML(data);
            }
        });
    }
    </script>

Template after SSR (something like this, you get the point)

<div id="content">
  <p>66</p>
  <button onclick='test(66)'>Test</button>
</div>

<script>
function test(next){
    $.ajax({
        url:'/test/'+next,
        type: 'GET',
        success: function(data){
            document.querySelector('#content p').innerHTML(data)
        }
    });
}
</script>

Upvotes: 3

Related Questions