Performing AJAX requests with jQuery

Edit the images/image/detail.html template of the images application, and consider the following line:

{% with total_likes=image.users_like.count %}

Replace the preceding one with the following one:

{% with total_likes=image.users_like.count users_like=image.users_like.all %}

Then, modify the <div> element with the image-info class, as follows:

<div class="image-info">
<div>
<span class="count">
<span class="total">{{ total_likes }}</span>
like{{ total_likes|pluralize }}
</span>
<a href="#" data-id="{{ image.id }}" data-action="{% if
request.user in users_like %}un{% endif %}like"
class="like button">

{% if request.user not in users_like %}
Like
{% else %}
Unlike
{% endif %}
</a>
</div>
{{ image.description|linebreaks }}
</div>

First, we added another variable to the {% with %} template tag in order to store the results of the image.users_like.all query and avoid executing it twice. We display the total number of users that like this image and include a link to like/unlike the image: we check whether the user is in the related object set of users_like to display either like or unlike, based on the current relationship between the user and this image. We add the following attributes to the <a> HTML element:

  • data-id: The ID of the image displayed
  • data-action: The action to run when the user clicks on the link. This can be like or unlike

We will send the value of both attributes in the AJAX request to the image_like view. When a user clicks on the like/unlike link, we will need to perform the following actions on the client side:

  1. Call the AJAX view, passing the image ID and the action parameters to it.
  2. If the AJAX request is successful, update the data-action attribute of the <a> HTML element with the opposite action (like / unlike), and modify its display text accordingly.
  3. Update the total number of likes that is displayed.

Add the domready block at the bottom of the images/image/detail.html template with the following JavaScript code:

{% block domready %}
$('a.like').click(function(e){
e.preventDefault();
$.post('{% url "images:like" %}',
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if (data['status'] == 'ok')
{
var previous_action = $('a.like').data('action');

// toggle data-action
$('a.like').data('action', previous_action == 'like' ?
'unlike' : 'like');
// toggle link text
$('a.like').text(previous_action == 'like' ? 'Unlike' :
'Like');

// update total likes
var previous_likes = parseInt($('span.count .total').text());
$('span.count .total').text(previous_action == 'like' ?
previous_likes + 1 : previous_likes - 1);
}
}
);
});
{% endblock %}

The preceding code works as follows:

  1. We use the $('a.like') jQuery selector to find all <a> elements of the HTML document with the like class.
  2. We define a handler function for the click event. This function will be executed every time the user clicks on the like/unlike link.
  3. Inside the handler function, we use e.preventDefault() to avoid the default behavior of the <a> element. This will prevent the link from taking us anywhere.
  4. We use $.post() to perform an asynchronous POST request to the server. jQuery also provides a $.get() method to perform GET requests and a low-level $.ajax() method.
  5. We use Django's {% url %} template tag to build the URL for the AJAX request.
  6. We build the POST parameters dictionary to send in the request. These are the ID and action parameters expected by our Django view. We retrieve these values from the <a> element's data-id and data-action attributes.
  7. We define a callback function that is executed when the HTTP response is received; it takes a data attribute that contains the content of the response.
  8. We access the status attribute of the data received and check whether it equals ok. If the returned data is as expected, we toggle the data-action attribute of the link and its text. This allows the user to undo their action.
  9. We increase or decrease the total likes count by one, depending on the action performed.

Open the image detail page in your browser for an image you have uploaded. You should be able to see the following initial likes count and the LIKE button, as follows:

Click on the UNLIKE button. You will note that the total likes count decreases by one and the button text changes to UNLIKE, as follows:

When you click on the UNLIKE button, the action is performed, the button's text changes back to LIKE, and the total count changes accordingly.

When programming JavaScript, especially when performing AJAX requests, it is recommended that you use a tool for debugging JavaScript and HTTP requests. Most modern browsers include developer tools to debug JavaScript. Usually, you can right-click anywhere on the website and click on Inspect element to access the web developer tools.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset