htmx icon indicating copy to clipboard operation
htmx copied to clipboard

JSON response from hx-post?

Open otonoton opened this issue 1 year ago • 1 comments

Is there a way to get a pre-parsed JSON response in the after-request handler? I assume it's simply not setting responseType="json" in the XHR.

Thanks

otonoton avatar Feb 22 '25 18:02 otonoton

Hey,

Disclaimer: didn't test the following at all

I assume it's simply not setting responseType="json" in the XHR

Well honestly I think it might really be this simple! See XMLHttpRequest: responseType property.

You could hook to the htmx:beforeSend event and override the value of event.detail.xhr.responseType

If you only need to do that for certain requests, you could also check if event.detail.requestConfig.headers contains a Accept header set to application/json for example.

You could then implement a custom extension to automatically do that for certain elements, or roll your own logic as to when to set the response type to JSON or not.

Hope this helps!

Telroshan avatar Feb 23 '25 07:02 Telroshan