Search code examples
javascriptpythondjangoajaxjinja2

update the 'div' after ajax request


This is my first project in django. I'm new to Django, ajax, javascript. I have to send the data to jinja template after making ajax request.

My index.html is

{% if data %}
  <p>{{data.title}}</p>
  <p>{{data.price}}</p>
{% endif %}

My javascript is

<script>
 $.ajax({
        type: "POST",
        url: "/",  // Replace with the actual URL of your view
        data: {
            input_value: "test",
            csrfmiddlewaretoken: "{{ csrf_token }}"
        },
        success: function(response) {
            title = response // after request, response be like { "data" : {"title":"t1", "price":20} }
        },
        error: function() {
            console.log("Error")
        }
    });

<script>

I don't know this is possible. Some using element.innerHTML to update, but i need to send to jinja format. Thanks


Solution

  • You have 2 options here and it depends on what do you prefer.

    1. Return a template and not a JSON The idea here is that you generate the template on the server side. and then return the resultant HTML to the AJAX caller. and so the Ajax success is just to append this HTML segment in the right place.

    2. Render the div in JS If you have JSON only policy or using DRF, then your only way is render the JSON using js code which loops over received items and generates the equivalent HTML, and then add it to the document.

    You can't put the JinJa on the same page because you didn't receive the data when the page where generated to render it.