How to get url for htmx get from an SSE event which itself triggers the hx-get call?

I am using django with django-channels and htmx.

In certain cases, my django views will send an SSE event to a user subscribed to the relevant channel, like a notification for example. Some of those events (depending on event name) needs to trigger a modal pop-up (like a rating modal after an e-commerce order or service completes).

I have implemented the requirements of the server-side event and data generation. I want to use the htmx sse extension on the frontend (django template).

My problem is, I want to get an event, let's say order_complete, and use that to trigger an hx-get call to a particular url which will be sent by the sse event. That hx-get's response will then be placed in the placeholder where modal view logic exists.

I have very little knowledge of JavaScript and not all that much more on htmx. I've looked at out of band swaps but I'm not sure if that's what I need.

I'd appreciate any opinion or suggestions for proceeding including a non-htmx solution if it's better performing or easier.

Thank you.

You can append parameters to a (fixed) url.

In a client side javascript handle the sseMessage event.


    document.body.addEventListener('htmx:sseMessage', function (evt) {

        //* check if this event is the one you want to use
        if (evt.detail.type !== "order_complete") {
            return;
        }

        //* If a JSON string was sent, leave it as it is 
        //evt.detail.elt.setAttribute("hx-vals", evt.detail.data);

        //* if not
        var msg = {};
        msg.orderId = evt.detail.data;   
        evt.detail.elt.setAttribute("hx-vals", JSON.stringify(msg));
    });

see https://htmx.org/attributes/hx-vals/

resulting url if evt.detail.data was 123:

/orders/showmodal?orderId=123

the html:

    <div hx-ext="sse" sse-connect="/sse-something">
        <div hx-get="/orders/showmodal"
                hx-trigger="sse:order_complete"
                hx-swap="innerHTML"
                hx-target="#idModalPlaceholder">
        </div>
    </div>

Update
You can also use an event listener just for order_complete.


    document.body.addEventListener('sse:order_complete', function (evt) {

        //* If a JSON string was sent, leave it as it is 
        //evt.detail.elt.setAttribute("hx-vals", evt.detail.data);

        //* if not
        var msg = {};
        msg.orderId = evt.detail.data;   
        evt.detail.elt.setAttribute("hx-vals", JSON.stringify(msg));
    });
Back to Top