Is It Possible To Pass Ajax Response As Template Context Variable In Django?
I sent an Ajax request to server to get some filtered data and here is a sample I receive from server: (3) [{…}, {…}, {…}] 0: {id: 1, title: '12 Rue Longueil', slug: '12-rue-
Solution 1:
Yes, you can. Basically the idea is to make a separate HTML file that's going to be rendered by the view that handles the AJAX request. Then, you can use JavaScript and the insertAdjacentHTML()
function to insert it in your original HTML file.
Take a look at this example:
view:
def ajax_handler(request):
# ... logic
return render(request, 'newHtmlFile.html', {'your_context': data})
Original HTML file
<div id='container'>
</div>
newHtmlFile.html
<p>{{ your_context }}</p>
JavaScript part (in this example I use Vanilla, not JQuery)
let ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if (this.readyState === 4){
if (this.status === 200){
document.querySelector('#container').insertAdjacentHTML('beforeend', this.responseText);
}
}
}
ajax.open('GET', '/ajax-handler-url', true);
ajax.send();
If you are interested to know how this works, we can break it down as follows:
- You have some data (like a queryset, in your case) in your view
- You call the
render()
method and you pass that data as the context data to a template - The
render()
method what actually does is to (let me be redundant here) render a HTML file (combining the HTML itself with the context data you passed) and return aHTTPResponse
object containing a rendered text. - That rendered text (which is a bytestring that represents the content of the rendered HTML) is given as a response to the client. In this case, it's given specifically to the
$.ajax()
function that made the request. - We use the
insertAdjacentHTML()
function to append that rendered text to the desired element (in the example above, the#container
div).
Solution 2:
A quick, and possibly "dirty", way of doing it is to use the backtick strings in javascript:
success: function (r) {
const listings = JSON.parse(r); // with the correct headers from django, this should't be needed.
listings.forEach(e => $('#content').append(`
<div class="listing mgb-1">${e.title}</div>
`));
}
You should return your data from django with the appropriate headers so you automatically get json and don't need to eval(response)
.
Post a Comment for "Is It Possible To Pass Ajax Response As Template Context Variable In Django?"