Reputation: 69
In my template I have list retrieved from the server:
{% for elem in event_list %}
<li id="item{{forloop.counter}}">
<a>...</a>
<button onclick="fetch({{elem.id}})">...</button>
{{ elem.id }}
{{ elem.name }}
</li>
{% endfor %}
When I click on the button I call the server to fetch some new information and want to update that specific list item with the newly retrieved information. How could I do that?
My javascript is as follows:
function fetch(elem_id){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resp = JSON.parse(xhr.responseText);
document.getElementById("item"+elem_id).innerHTML = resp;
}
};
url = SERVER_URL
xhr.open('GET', url, true);
xhr.send();
}
I made the server return a dictionary which in javascript is then seen as a JSON object, but I can't successfully update the list item.
Any help is appreciated
Upvotes: 3
Views: 882
Reputation: 2146
I think the issue here is, you're trying to return a list, and then build the list with django template loops. You can probably jump through a few hoops and do this by doing some jquery conditional where you include another HTML file within your page after a response is returned...but either way you're going to have to use jquery & django so I'm not sure why that approach would be any cleaner.
To do this, I would use an AJAX handler on your button to run a django function, and return a json response that contains the list, which you can use jquery to build your ul from.
In Django:
def list_return_function(request):
//logic
updated_list = [...]
response_data = json.dumps({'list_data':updated_list)})
return HttpResponse(response_data, content_type='application/json')
Jquery Handler:
$( button_selector ).on('click', function() {
//some logic maybe
old_list = [...]
$.ajax({
url: "/site_url/django_function_url/",
type: "POST",
data: {data: old_list,},
success:function(data) {
//your returned python list
new_list = data['list_data']
//Now, loop through the new_list and append these items wrapped in <li> tags to your ul.
}
});
});
This is pretty bare bones, but maybe you'll get the idea. If this totally sucks, and doesn't help, let me know why and I'll try to make it clearer.
So it depends what you your python function is returning on what you want to do with jquery. Is it returning the full, new list, or just new items that need to be updated. If it's returning the full new list, I would clear the html, and rebuld it. But I added in the basic
Upvotes: 2