## Effortlessly Implement Robust Asynchronous Communication with the Server {#sec-b77e387924b4} [[HTMX]] enables the implementation of powerful asynchronous features in server-centric web development frameworks like Django, all without the complexities of [[JavaScript]]. In this installment, we will explore the **internal workings of how HTMX handles Ajax requests** and **how it communicates with actual Django views** through concrete examples. ![Conceptual diagram of HTMX Ajax communication](/media/whitedec/blog_img/bd86a3db8e1c4c409a777cf86a8047f7.webp) ## The Essence of [[HTMX]]: HTML is the Message {#sec-fcb60a4b40b4} Traditional Ajax communication (e.g., axios, fetch) involves receiving JSON data from the server, which JavaScript then interprets to re-render the screen. However, HTMX adheres to the **'Hypermedia as the Engine of Application State (HATEOAS)'** principle. This means the server sends **ready-made HTML fragments** instead of data (JSON), and HTMX simply 'swaps' them into the specified location. **4 Steps of HTMX Ajax Communication** 1. **Event Trigger:** The user interacts with an HTML element (e.g., a button). 2. **Ajax Request:** HTMX invokes the browser's `fetch` API to send a request to the server. 3. **HTML Response:** After processing the logic, the server returns only the **necessary HTML fragment**, not the entire page. 4. **DOM Swap:** HTMX immediately inserts the received HTML into the element specified by `hx-target`. ## Practical Example: Implementing a "Like" Button {#sec-5eb5b07b3b51} Beyond just changing a number, let's explore how HTML fragments are exchanged between the server and client. ### 1. Frontend (Template) {#sec-cad7db10ba2b} This approach involves sending a request with `hx-post` and replacing the entire `#like-section` with the response from the server. ```html
``` When `hx-target` and `hx-swap` are explicitly defined within the HTML tags, as in this example, you can immediately understand "what changes where when this button is clicked" without having to search through JavaScript files when rereading the code later. Personally, while it might be slightly inconvenient to delve into the backend's View function to understand the code, the presence of `hx-` attributes directly within the HTML tag, as shown above, suggests it might be superior in terms of **Locality of Behavior** compared to inline JavaScript. ### 2. Backend (Django View) {#sec-1fda4c57da3b} The crucial point here is that we use **`render` instead of `JsonResponse`**. ```python from django.shortcuts import render def like_post(request): # 좋아요 로직 처리 (예: DB 업데이트) new_count = 10 # 전체 페이지가 아닌, 버튼 부분만 포함된 작은 템플릿 조각을 반환합니다. return render(request, 'partials/_like_button.html', { 'likes_count': new_count }) ``` ## 3. Partial Template for Response {#sec-ce5390bdc052} This is the 'HTML fragment' that the server will deliver to the client. Since `hx-swap="outerHTML"` is configured, this content will replace the entire existing `#like-section`. ```HTML
``` ### Why this approach? (Understanding the Principle) {#sec-67af112c65f1} In the traditional approach, after receiving `JsonResponse({'likes': 10})`, you would have to write JavaScript code like `document.getElementById('count').innerText = data.likes`. However, the [[HTMX]] approach offers: 1. **Prevents Logic Fragmentation:** The server (Django template) manages the definition of "how the screen should change when a like button is pressed." 2. **Data-View Synchronization:** Since the HTML sent from the server is directly injected into the display, errors that occur when processing data on the client side are eliminated. ## Concluding This Part {#sec-b28d1b5245c5} Using [[HTMX]] is not merely about reducing code; it's a return to leveraging the web's intrinsic capability of 'Hypermedia (HTML)' to its fullest. This allows developers to escape the complexities of JavaScript state management and focus more on server-side logic. **Read Related Posts** : - [Simplifying Dynamic Web Development with Django and HTMX (Part 1)](/ko/whitedec/2025/1/27/django-htmx-dynamic-web-simplification/) - [Simplifying Dynamic Web Development with Django and HTMX (Part 3)](/ko/whitedec/2025/1/27/django-htmx-dynamic-web-simplification-3/) - [Simplifying Dynamic Web Development with Django and HTMX (Part 4): CSRF Token Integration](/ko/whitedec/2025/1/27/django-htmx-csrf-token-integration/) - [Simplifying Dynamic Web Development with Django and HTMX (Part 5): Advanced Features](/ko/whitedec/2025/1/27/django-htmx-advanced-features/) - [Simplifying Dynamic Web Development with Django and HTMX (Part 6): HTML Response Method](/ko/whitedec/2025/1/27/django-htmx-html-response/) - [Simplifying Dynamic Web Development with Django and HTMX (Part 7): JSON Response Method](/ko/whitedec/2025/1/27/django-htmx-json-response/)