0

I have a simple code in my template.html:

    <div>
        <input type="button" id="buttonId" value="Show Data">  
    </div>
    <script>
        $('#buttonId').click(function() {    
            $.ajax({
                method: 'POST',
                data: {
                    csrfmiddlewaretoken: csrf_token,
                    click: true
                },
                success: function(response){
                    console.log(response) // it is a HTML, not my data
                }
            });
        });
    </script>
    {{results}} 

And in my views.py:

    if request.POST.get('click', False):
        ... #here I get finalresults
        return render(request, 'template.html', context={
            'results': finalresults
        })

When I push the Button, the script runs. So I know that after pushing the button, finalresults has content, but this content does not arrive to the HTML template.

What am I doing wrong?

0

1 Answer 1

2

console.log(response) // it is a HTML, not my data

You are getting HTML because you are rendering the whole template.

I think you just want to return results. In this case, just change:

return render(request, 'template.html', context={
    'results': finalresults,
})

To:

from django.http import JsonResponse
...
...
return JsonResponse(
    {'results': finalresults},
)    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.