Reputation: 529
In a template I am displaying database objects called posts
like this:
{% for post in posts %}
....
....
<div class="pull-left">
<span class="badge" >
<p class="post-points">{{post.points}}</p>
</span>
</div>
...
...
{% endfor %}
Now with an ajax request Id like change the post.points
attribute of a particular post
object. I have managed to send and receive ajax requests but not able to understand how to select a post
object and change its post.points
value.
for explanation purpose assume this is the json response from server after processing ajax request:
{'post_id': some post's id,
'post_points': some value}
Hope im making my self clear. Please help.
Upvotes: 0
Views: 1996
Reputation: 18447
I'd probably go with something like this:
<p class="post-points" id="{{ post.pk }}">{{ post.points }}</p>
Then I have an anchor to grab the post pk from each dom elemnt. You send it along with the ajax, so the server knows what post you're talking about, and you then replace the value within that <p>
tag with the response.
Edit
Let's say this call happens when you click on any point:
$('.post-point').on(click, function() {
var point = $(this),
pk = point.attr('id'),
csrf = getCookie('csrftoken');
data = {'pk': pk, 'csrfmiddlewaretoken': csrf }
$.ajax({
url: 'post_url',
data: data,
type: 'post',
success: function(data) {
point.html(data);
}
});
});
Now this is a very general example, you probably need to change it a lot. Maybe you need the badge to be the clickable object, you probably want to send some more data. I took a guess that you mean to send an ajax request with a type of 'post' since you mentioned the data is changing, in which case you have to include the csrf token as well (the function getCookie I'm using is taken from the django docs, see here), and you might want to pass it as a header and not as part of the post data.
Also, the data which is returned doesn't have to be json, it depends on what you need to do with it on the client side - if it's simple as sending a number or some text then you can use simple HttpResponse, but if it's an object you want to iterate over using javascript you want to use json.dumps on server side and then $.parseJSON(data)
on server side.
Also, don't forget to create a function for what happens if the ajax request fails (google it). I think that you can pick it up from here
Upvotes: 2