Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Update Page Information Without Refreshing

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?

like image 977
iFengo Avatar asked May 29 '17 21:05

iFengo


1 Answers

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
      }
    })
  };
like image 81
Ilario Pierbattista Avatar answered Sep 19 '22 12:09

Ilario Pierbattista