DEV Community

Cover image for Simple Introduction To HTMX
Ethan
Ethan

Posted on • Originally published at ethan-dev.com

Simple Introduction To HTMX

Introduction

Hello! 😎

In the ever-evolving landscape of web development, where the lines between server and client-side scripting blur, a tool named HTMX has emerged.

It offers simplicity for those weary of the complexity required by heavy JavaScript frameworks. HTMX allows you to harness the power of AJAX, WebSockets, and server-sent events with nothing but HTML, enabling you to create web pages with minimal effort.


What is HTMX?

HTMX is a small, yet powerful JavaScript library that extends HTML's capabilities enabling dynamic updates to the web page without needing to write JavaScript. Inspired by the principles of progressive enhancement and unobtrusive JavaScript. HTMX allows you to create modern, user-friendly web applications. It's designed to be an ally that empowers your HTML to perform tasks you never thought possible, while keeping the complexity at bay.

Imagine a world where you can update parts of your webpage, submit forms, and react to server-side events with straightforward HTML attributes. That's the realm HTMX offers to transport you to, a place where the web is fast, responsive and elegant, all without a single line of JavaScript. 😆


Advantages of HTMX

HTMX has a variety of advantages including but not limited to the following:

  • Ease of Use: It's like HTML on steroids, but easier to manage than traditional JavaScript frameworks
  • Lightweight: No large downloads, allowing your site to be speedy
  • Progressive Enhancement: Works right on top of your existing HTML, making progressively enhanced

Creating a Simple Login Form

First we will create a simple backend PHP file to handle the request. Create a new file called "login_handler.php" and populate it with the following:

<?php
$username = $_POST['username'];

echo '<p>Welcome, ' . htmlspecialchars($username) . '</p>';
?>
Enter fullscreen mode Exit fullscreen mode

Since the focus is on HTMX the above is nothing to complicated. All it does is display what the user entered into the username field. Normally you would want authentication etc. But I will leave that challenge to you.

To demonstrate HTMX lets create a simple login form that will be styled using bootstrap. Create a new file called "index.html" and populate it with the following, don't worry I will explain what the code does below.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Login Form</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    </head>

    <body>
        <div class="container mt-5">
            <div class="row justify-content-center">
                    <div class="col-md-6">
                        <form hx-post="login_handler.php" hx-target="#login-response" hx-swap="outerHTML" class="card p-4">
                        <div class="mb-3">
                            <label for="username" class="form-label">Username:</label>
                            <input type="text" id="username" name="username" required class="form-control">
                        </div>

                        <div class="mb-3">
                            <label for="password" class="form-label">Password:</label>
                            <input type="password" id="password" name="password" required class="form-control">
                        </div>

                        <button type="submit" class="btn btn-dark">Log In</button>
                    </form>
                    <div id="login-response"></div>
                </div>
            </div>
        </div>
    </body>

    <script src="https://unpkg.com/htmx.org"></script>
</html>
Enter fullscreen mode Exit fullscreen mode

In the header we import the bootstrap stylesheet.
After that we create the login form hx-post tells the form to submit its data to "login_handler.php" which is the back end via POST request.

The hx-target and hx-swap attributes work together to update the content of the page with the server's response. When the user clicks on the login button, HTMX leaps into action sending the form data to the server and displaying the response within the "login-response" div, all without refreshing the page. 😁


Running The Example

To display the above page you can use the following php command:

php -S localhost:8000
Enter fullscreen mode Exit fullscreen mode

This will fire up a simple HTTP server, next access the page via:
http://localhost:8000

Image of login form

Try entering a username and password and click the login button. The response will instantly appear.

Image of logged in form


Conclusion

Here I have given a very simple introduction to HTMX. I hope you have learned something from this. I am also very new to HTMX but I do enjoy learning it.

If you have any good resources please feel free to share them.

As always you can find the example code on my Github:
https://github.com/ethand91/simple-htmx-form

Happy Coding! 😎


Like my work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee.

“Buy Me A Coffee”

If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the [following course](https://algolab.so/p/algorithms-and-data-structure-video-course?affcode=1413380_bzrepgch

Top comments (6)

Collapse
 
imthedeveloper profile image
ImTheDeveloper

Yep really like htmx. I added alpine.js for the small bits of interactivity I need where it would be overkill to talk to the server

Collapse
 
ethand91 profile image
Ethan

I didn't know about alphine! Thanks for telling me, I'll give it a look :)

Collapse
 
clsource profile image
Camilo

HTMx is a good tool but it lacks several other functionalities, in my opinion is just jQuery improved.

If you are curious about functional programming I highly recommend Elixir and Phoenix LiveView.

reddit.com/r/elixir/comments/198cg...

Here is an interview with Jose and he talks about HTMx and Hotwire meaning that they are Imperative tools.

Collapse
 
ansonnn07 profile image
Ansonnn

If everything is in HTML, wouldn't the user be able to make changes to the HTML to change especially things like a PHP script to trigger? It seems dangerous if the random script name somehow triggered something in the backend

Collapse
 
pontakornth profile image
Pontakorn Paesaeng

If user can make HTML, that would be vulnerable. Usually, there is an escaping feature on most common templating languages anyway. Escaping the user content would be enough to prevent that.

If some HTML or anything rendered to HTML is necessary, the developers need to allow only safe attributes. It is like how to prevent XSS in traditional web applications.

Collapse
 
arturstorsters profile image
Artūrs

good point