Skip to content

Instantly share code, notes, and snippets.

@prdoyle
Last active August 5, 2024 03:30
Show Gist options
  • Save prdoyle/4fbffab5f78c5d3ec64ee068c6d4e337 to your computer and use it in GitHub Desktop.
Save prdoyle/4fbffab5f78c5d3ec64ee068c6d4e337 to your computer and use it in GitHub Desktop.
HTMX extension for JSON
<script>
(function() {
htmx.defineExtension('ContentTypeJson', {
onEvent: function(name, evt) {
if (name === "htmx:configRequest") {
evt.detail.headers['Content-Type'] = 'application/json';
}
else if (name === "htmx:beforeRequest") {
evt.detail.xhr.send(evt.detail.elt.getAttribute("hx-json"))
}
}
});
})();
</script>
... and then ...
<button
hx-put="/url/example/path"
hx-ext="ContentTypeJson"
hx-json="{'this here': 'is json'}"
>Submit</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment