I should get data from ajax, pass it to class that render this html page and update data, but don’t refresh the page. I get this data from ajax but I can’t pass it to Context.
I have this html:
{% extends 'main/base.html' %}
{% load static %}
{% block content %}
<div class="container">
<div class="choose_buttons">
<a href="{% url 'start_game' %}"
hx-get="{% url 'start_game' %}"
hx-target=".view_page">
<div class="play_keys" id="paper"><img src="{% static 'main/img/paper.jpeg' %}" alt=""></div></a>
<a href="{% url 'start_game' %}"
hx-get="{% url 'start_game' %}"
hx-target=".view_page"><div class="play_keys" id="scissor"><img src="{% static 'main/img/scissor.jpeg' %}" alt=""></div></a>
<a href="{% url 'start_game' %}"
hx-get="{% url 'start_game' %}"
hx-target=".view_page"><div class="play_keys" id="rock"><img src="{% static 'main/img/rock.jpeg' %}" alt=""></div></a>
</div>
key: {{ some_data }}
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$(".play_keys").off().on('click', function() {
var id = $(this).attr("id");
$.ajax({
url: "{% url 'get_playbutton' %}",
type: "GET",
cache: false,
data: { "id": id },
success: function(response) {
},
});
});
});
</script>
{% endblock %}
views.py:
def ajax_get_playbutton(request):
id_button = request.GET.get("id")
game_ = startGame()
game_.playground(id_button)
return HttpResponse("ok")
class startGame(TemplateView):
template_name = 'main/game_field.html'
def playground(self, key):
self.choose = key
#another data ...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['choos_data'] = self.choose
return context
urls.py:
urlpatterns = [
path('game-room', views.startGame.as_view(), name= "start_game"),
path('ajax_get_playbutton', views.ajax_get_playbutton, name= "get_playbutton"),
]