HTMX get post AJAX Example for WordPress

Fetch WordPress Post

<script src="https://unpkg.com/htmx.org@1.9.6"></script>

<!-- Bootstrap for Styling (Optional) -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="container">
  <h2 class="text-center">Fetch WordPress Post</h2>

  <!-- Input for Post ID -->
  <label for="post-id" class="form-label">Enter Post ID:</label>
  <input type="number" id="post-id" class="form-control" placeholder="Enter WordPress Post ID: 8031">

  <!-- Fetch Button -->
  <button 
          class="btn btn-primary mt-3"
          id="fetch-post-btn">
    Get Post
  </button>

  <!-- Loading Indicator -->
  <div id="loading-spinner" class="text-center mt-3" style="display: none;">
    <div class="spinner-border text-primary" role="status"></div>
  </div>

  <!-- Post Content (Dynamically Updated) -->
  <div id="post-content" class="mt-4"></div>
</div>

<!-- JavaScript to Fetch Post Data -->
<script>
  document.getElementById("fetch-post-btn").addEventListener("click", function() {
    let postId = document.getElementById("post-id").value;

    if (!postId) {
      alert("Please enter a valid Post ID.");
      return;
    }

    let url = `https://sinanisler.com/wp-json/wp/v2/posts/${postId}`;
    
    // Show loading spinner
    document.getElementById("loading-spinner").style.display = "block";
    
    fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error("Post not found.");
        }
        return response.json();
      })
      .then(postData => {
        let title = postData.title?.rendered || "No Title";
        let content = postData.content?.rendered || "No Content";
        
        // Sanitize HTML content properly
        let sanitizedContent = new DOMParser().parseFromString(content, "text/html").body.innerHTML;
        
        document.getElementById("post-content").innerHTML = `
          <h3>${title}</h3>
          <div>${sanitizedContent}</div>
        `;
      })
      .catch(error => {
        document.getElementById("post-content").innerHTML = `<p class="text-danger">Error: ${error.message}</p>`;
      })
      .finally(() => {
        // Hide loading spinner
        document.getElementById("loading-spinner").style.display = "none";
      });
  });
</script>