Dynamic Modal Content

Hi Ken,
I came across this thread:

And was hoping you might be able to explain this bit:

Create a view that returns the html fragment that you want displayed in your pop-up.

I have a roadmap page with roadmap items. I’m trying to find a way that when a user clicks on the roadmap item it would open a modal with the content of that item.

I’m using the modal in Bootstrap and can get the modal open when a button is clicked but it’s getting the content into the modal I am struggling with.

The basic view i was thinking would be

def roadmap_item_view(request, id):
    roadmap_item = Roadmap.objects.get(pk=id)
    short_description = roadmap_item.description

    return render(request, 'pages/roadmap_item.html',{'roadmap_item':roadmap_item,'short_description':short_description})



Are you using any sort of JavaScript library or framework such as jQuery or HTMX? (If so, my answer would be different than if you’re limited to raw JavaScript.)

I am using jQuery to make the request to the view, i’ve been trying this. But i don’t think this is the correct way to do it

    $(document).ready(function() {
      $("#apiLink").click(function(event) {

        var modalContentElement = $("#modalContent");
        // Make your AJAX request
          url: 'api/roadmap/1',  
          method: 'GET',
          success: function(response) {
            // Update the modal content with the fetched HTML
            // Show the modal
          error: function(error) {
            console.error('API error:', error);

I don’t think i should be using jquery to render the content in the modal ? I was thinking that i should still be able to use the context from the view?

Superficially that looks correct - except I think that the $("#modalContent") expression is going to return a list and not the element. You might want to check that. That means you may want the assignment statement to be modalContentElement[0].html(response) - but that’s just a guess as I’m winging this at the moment.

If that’s not working, then I’d use the debugging features in the browser to put a breakpoint on at the modalContentElement.html(response) statement to look at what modalContentElement and response are, to verify that they’re what you think they should be.

You’re not. The view is rendering the content and returning html as the response.

Ok got it working. Thanks, Ken.