I have a Django template whereby I am looping through several items in the homepage. When an item is clicked, a modal which I have included by importing it should be shown and data related to the clicked item displayed. I am using JSONResponse to prepopulate the modal. Once the modal is shown, I want to create a checkout session which will require the id of the item being referred to in the modal. I am stuck at how to get the id.
Here is the script for showing the modal and prepopulating it:
let modal = document.getElementById("modal");
modal.style.display = "none";
function modalHandler(val, content_id) {
if (val) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
let data = JSON.parse(this.responseText);
document.getElementById("subtotal").innerHTML = data.subtotal;
document.getElementById("taxes").innerHTML = data.taxes;
document.getElementById("website_fee").innerHTML = data.website_fee;
document.getElementById("total").innerHTML = data.total;
fadeIn(modal);
}
};
xhr.open("GET", "/modal-content/" + content_id + "/", true);
xhr.send();
} else {
fadeOut(modal);
}
}
Here is the views.py which returns the JSON data:
def modal_content_view(request, content_id):
my_model = get_object_or_404(MyModels, content_id=content_id)
print(f"the model is {my_model.username}")
data = {
'subtotal': my_model.username,
'taxes': '2.60',
'website_fee': '0.87',
'total': '23.47',
'content_id':my_model.content_id
}
return JsonResponse(data)
Here is the script that is supposed to fetch the data when the checkout button is clicked:
<script type="text/javascript">
var checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', function() {
fetch("{% url 'checkout' content_id %}", {
method: 'POST',
data: JSON.stringify({
amount: "{{ cost }}" * 100,
description: "{{ title }}",
gig_id: "{{ gig_id }}",
}),
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error('Error:', error);
});
});
</script>
Here is the view that handles the content_id passed from the script above:
@csrf_exempt
def create_checkout_session(request, content_id):
model = MyModels.objects.get(content_id=content_id)
subscription = Subscription(model=model, is_subscribed=False, user=request.user)
And here is the onclick function that triggers the modal to show:
onclick="modalHandler(true, '{{content.model.content_id}}')"
My question is how do I pass the ‘content_id’ from the modal to the script that handles checkout