0

I'm using django and ajax to build a small app.

I send some data by ajax:

// send search post when clicking the button
$("#search-button").click(function(){
    $.post(
        "{% url 'search-index' %}",
        {
            query: $("#query").val()
        },
        function(data, status){
            console.log("success")
        }
    )
})

And I generate some new data according to the query, which I'd like to display in the html template:

def view(request):
    if request.method == "POST":
        query = request.POST["query"]
        hits = search(query)

        return render(request, "search/index.html", {"hits": hits})
{% if hits %}
    <div class="container">
    {% for hit in hits %}
        <div>
            <a href="">{{ hit.title }}</a>
        </div>
        <div>
            <p>{{ hit.abstract }}</p>
        </div>
    {% endfor %}
    </div>
{% endif %}

However, I find django is not rendering the template, I got an empty html page after this post request. I don't want to append the data using jquery. I prefer to modify the html in the template.

Any solution? Thanks in advance.

namespace-Pt
  • 1,604
  • 1
  • 14
  • 25
  • Are you sure your 'hits' object is creating anything? Your template has an if-statement which would not render anything if hits is empty or returns None. What does your search function do? – 0sVoid Jul 11 '22 at 14:15
  • Yes it indeed creates a non-empty list. I tried to just assign a list to hits but nothing appears in the rendered html. – namespace-Pt Jul 11 '22 at 14:18
  • Can you double check if anything is rendered by adding some html like divs around your response content, just for debug purposes. The code itself seems ok. – mariodev Jul 11 '22 at 15:55
  • Yes, I checked. This seems to be a common issue as put [here](https://stackoverflow.com/questions/50961625/django-render-template-on-ajax-success) and [here](https://stackoverflow.com/questions/70652414/how-to-render-django-template-after-ajax-call). However I can't find a satisfactory solution. – namespace-Pt Jul 11 '22 at 16:13

1 Answers1

0

I found it is actually impossible. The django template is rendered from the serve side, while the ajax is parsed from the client side and is asynchronous.

namespace-Pt
  • 1,604
  • 1
  • 14
  • 25