7

I've been trying to make this portion of my website update whenever a button is pressed:

Coins

In my template, I access this information through {{ request.user.profile.coins }}:

<span class="status">Balance:&nbsp;{{ request.user.profile.coins }}
  <img class="coin-img" src="{% static 'assets/coin.png' %}" height="40px" width="auto">
</span>

I was looking into the process and I attempted to use an AJAX function to call this view:

@login_required(login_url='users/login')

def coin_increase(request):
    """
    Function based view for increasing a user's coin balance
    """
    if request.is_ajax():
        try:
            user = request.user
        except User.DoesNotExist:
            raise Http404("No user matches the given query.")
        user.profile.coins += 5
        user.save()
        return render(request, 'home.html', {'home': home})
    else:
        raise Http404

The AJAX function is as follows:

function update_coins() {
    $.ajax({
      method: "POST",
      url: "/coins",
      data: {},
      success: function(data) {
        alert("test");
      }
    })
  };

How can I get this to work?

Ilario Pierbattista
  • 3,175
  • 2
  • 31
  • 41
iFengo
  • 177
  • 2
  • 3
  • 12

1 Answers1

5

I guess that home.html is the template of the whole page, which contains the portion of interest.

The problem is here:

return render(request, 'home.html', {'home': home})

You don't need to render the whole page to update just that portion. You only need to know the new value for user.profile.coins. The most used technique is to serialize that data into a format that javascript can understand: JSON.

Not sure about what is your version of django, maybe this will work:

from django.http import JsonResponse
return JsonResponse({'coins':user.profile.coins})

Then:

function update_coins() {
    $.ajax({
      method: "POST",
      url: "/coins",
      data: {},
      success: function(data) {
        console.log(data) // check out how data is structured

        // Update the coin amount
        $('.status').contents()[0].textContent = 'Balance&nbsp'+data.coins
      }
    })
  };
Ilario Pierbattista
  • 3,175
  • 2
  • 31
  • 41
  • I get `Object { coins: 6725 }` in the console – iFengo May 29 '17 at 22:15
  • Good :) now, use jquery to select the DOM element containing the coin amount and update it with `data.coins`. If you're not familiar with jquery selectors, post your html and I'll help you – Ilario Pierbattista May 29 '17 at 22:19
  • My HTML looks like: ` Balance: {{ request.user.profile.coins }} – iFengo May 29 '17 at 22:22
  • Use `$('.status').contents()[0].textContent = 'Balance&nbsp'+data.coins`. See https://stackoverflow.com/questions/9956388/how-to-change-only-text-node-in-element for further informations – Ilario Pierbattista May 29 '17 at 22:31
  • For me it doe not work: here I have some questions: https://stackoverflow.com/questions/58060402/two-submit-inputs-within-one-form-and-ajax-in-django – Nessi Sep 24 '19 at 05:22