$htp

The $htp function is a custom JavaScript function designed to handle AJAX (Asynchronous JavaScript and XML) requests for dynamic content loading. It simplifies the process of fetching data from a server and updating specified HTML elements with the response content.

Syntax

$htp.call(element,dynamic_options,options);

Example Usage

<div
     htp-get="/content.html"
     htp-query='{"key":1,"id":"20"}'>
     Click me to fetch data
</div>
<script>
 document.querySelector("div").addEventListener("click",function(){
 $htp.call(this);
});
</script>

Example Usage (POST Request)

<div class="post"
      htp-post="/submit.php"
      htp-query='{"key":1,"id":"20"}'>
</div>

$htp.call()

// Call the $htp function with dynamic options
$htp.call(document.querySelector(".element"), { dynamic: "value" });

// Another example with additional static options
$htp.call(document.querySelector(".element"), { dynamic: "value" }, {
    "htp-get": "/hello.html",
   //  or... options
});

Explanation:

$htp Events

$htp triggers events during various stages of the HTTP request lifecycle. These events can be useful for tracking the progress of AJAX requests and performing actions based on the state of the request. Below are the events along with their descriptions:


1. htp-load

  document.querySelector(".element").addEventListener("htp-load", function() {
      console.log("Loading...");
  });

2. htp-loaded

  document.querySelector(".element").addEventListener("htp-loaded", function() {
      console.log("Content loaded...");
  });

3. htp-fail

  document.querySelector(".element").addEventListener("htp-fail", function() {
      console.error("Failed to load content.");
  });

dynamically Events

The provided CSS code dynamically adjusts the appearance of elements based on the presence of certain attributes (htp-on, htp-fail, htp-done) to reflect the state of an AJAX request managed by $htp. Here's a breakdown of what each part does:

  1. Display Loading Indicator during Loading:
   .target[htp-on] {
       /* Style for when loading */
   }
  1. Hide Dynamic Content and Error Message by Default:
   .target[htp-on] .dynamic,
   .target[htp-fail] .dynamic {
       display: none;
   }
   .page-error {
       display: none;
   }
  1. Display Error Message if Loading Fails:
   .target[htp-fail] .page-error {
       display: block;
   }
  1. Hide Loading Indicator when Loading is Done or Fails:
   .target[htp-done] .loading, 
   .target[htp-fail] .loading {
       display: none;
   }

Overall, these CSS rules provide a way to dynamically adjust the appearance of elements based on the state of an AJAX request, ensuring a better user experience by showing loading indicators and error messages appropriately.

htp-options

The htp-options attribute provides a comprehensive set of options for configuring AJAX requests made using the $htp function in JavaScript. These options allow developers to customize various aspects of the HTTP request, including request method, headers, success callback, error handling, and more.

List of htp-options

  1. htp-method: Specifies the HTTP method for the request (GET, POST, etc.).
  2. htp-t: Specifies the target element where fetched content will be inserted.
  3. htp-query: Specifies query parameters for the request.
  4. htp-headers: Specifies custom headers for the request.
  5. htp-s: Specifies the success callback function to handle the HTTP request's successful response.
  6. htp-swap: Specifies the property to update with the fetched content (e.g., innerHTML, append).
  7. htp-swap-s: Specifies the method for inserting fetched content (after, before, etc.).
  8. htp-status: Defines the expected status code for successful responses.
  9. htp-sync: Controls the synchronization behavior of HTTP requests triggered by htp-call.
  10. htp-ldr: Specifies a loading indicator or error message while the request is in progress or in case of failure.

Example Usage

<div 
  htp-get="/api/data"
  htp-method="GET"
  htp-t=".target"
  htp-query='{"category": "books", "page": 1}'
  htp-headers='{"Authorization": "Bearer YOUR_TOKEN"}'
  htp-s="handleSuccess"
  htp-swap="append"
  htp-swap-s="after"
  htp-status="200"
  htp-sync="true"
  htp-ldr=".loading-indicator"
></div>

Explanation

Best Practices

htp-ge` and htp-post

The htp-get and htp-post attributes are used in HTML elements to specify the URL for AJAX requests and the HTTP method to be used (GET or POST). These attributes are commonly used in conjunction with JavaScript functions such as $htp.call() to initiate AJAX requests and retrieve data from or send data to a server.

htp-get Attribute

The htp-get attribute is used to specify the URL for making HTTP GET requests. When an element with htp-get is activated (e.g., clicked), the JavaScript function associated with it (e.g., $htp.call()) will initiate a GET request to the specified URL.

Example Usage:
<div htp-get="/api/data">Click me to fetch data</div>
document.querySelector("div").addEventListener("click",function(){
 $htp.call(this);
});

htp-post Attribute

The htp-post attribute is used to specify the URL for making HTTP POST requests. Similarly to htp-get, when an element with htp-post is activated, it triggers a JavaScript function to initiate a POST request to the specified URL.

Example Usage:
<div  htp-post="/api/data"
htp-query='{"key":1,"id":"20"}'
>Click me to fetch data</div>
document.querySelector("div").addEventListener("click",function(){
 $htp.call(this);
});

Usage Notes:

htp-query

The htp-query attribute in an AJAX request specifies the query parameters to be sent along with the request. These parameters are typically used to customize the server's response based on the client's requirements. The htp-query attribute value should be a valid JSON object representing the query parameters.

Syntax:

<div
    htp-get="/api/data"
    htp-query='{"param1": "value1", "param2": "value2"}'
>
    <!-- AJAX Content -->
</div>

Example:

<div
    htp-get="/api/data"
    htp-query='{"page": 1, "limit": 10, "sort": "asc"}'
    htp-swap="innerHTML"
    htp-t=".data-container"
>
    <!-- Placeholder for AJAX Content -->
</div>

Explanation:

Notes:

Dynamic Values

In HTML, dynamic values can be injected into attributes using placeholders. These placeholders are then replaced with actual values using JavaScript before initiating AJAX requests. Here's an example demonstrating the usage of dynamic values:

<div
  class="content"
  htp-get="/api/data"
  htp-query='{"key":1,"id":"$id","user_name":"$name","total":"$total_number()"}'
>
  <!-- Dynamic Values -->
  <!-- $id: 12, $name: "barinty", $total_number(): 80 -->
</div>
<script>
  var id = 12;
  var name = "barinty";
  function total_number() {
    return 50 + 30;
  }
  $htp.call(document.querySelector(".content"), {
    id: id,
    /.............../ 
  });
</script>

Explanation:

This approach allows for flexible and dynamic generation of AJAX requests with varying parameters based on the context or user input.

htp-t target-element

The htp-t attribute is employed to specify the target element where fetched content will be inserted after a successful AJAX request. Below are examples illustrating different usage scenarios of htp-t.

Example 1: Using Class Selector

<div htp-get="/list.html" htp-t=".target"></div>
<div class="target">
  <!-- Placeholder for AJAX Content -->
</div>

Example 2: Using ID Selector

<div htp-get="/list.html" htp-t="#data"></div>
<div id="data">
    <h>hello world</h>
    <div htp-data="">
        <!-- Placeholder for AJAX Content -->
    </div>
</div>

Example 3: Using Tag Name and ID Selector

<div htp-get="/list.html" htp-t="#data2"></div>
<p id="data2" htp-data="">
    <!-- Placeholder for AJAX Content -->
</p>

Usage Notes:

These examples showcase how htp-t can be utilized to define the location where fetched content should be inserted in the HTML document following an AJAX request.

htp-status

The htp-status attribute in an AJAX request specifies the expected HTTP status code for a successful response. It allows you to define the specific status code that indicates a successful response from the server. If the response status code matches the one specified in htp-status, the success handler (specified using htp-s) will be executed.

Syntax:

<div
    htp-get="/api/data"
    htp-status="200"
    htp-s="handleSuccess"
>
    <!-- AJAX Content -->
</div>

Attributes:

Example:

<div
    htp-get="/api/data"
    htp-status="200"
    htp-s="handleSuccess"
>
    <!-- AJAX Content -->
</div>
<script>
    function handleSuccess(response,status) {
        console.log("Request successful!");
        console.log("Response:", response);
    }
</script>

Explanation:

Notes:

htp-headers

The htp-headers attribute in an AJAX request specifies additional HTTP headers to be included in the request sent to the server. These headers can provide various types of information, such as authentication tokens, content types, or custom headers required by the server to process the request properly.

Syntax:

<div
    htp-get="/api/data"
    htp-headers='{"HeaderName": "HeaderValue", "Authorization": "Bearer TOKEN"}'
>
    <!-- AJAX Content -->
</div>

Attributes:

Example:

<div
    htp-get="/api/data"
    htp-headers='{"Authorization": "Bearer YOUR_TOKEN", "Content-Type": "application/json"}'
    htp-swap="append"
    htp-t=".target-element"
>
    <!-- Placeholder for AJAX Content -->
</div>

Explanation:

htp-data

The htp-data attribute is used to indicate the location where fetched content will be inserted after a successful AJAX request. Here are examples illustrating different ways to use htp-data.

Example 1: Inserting Content Inside a <div> Element

<div htp-get="/api/fetch-data">
    <!-- dynamic content -->
</div>

Example 2: Inserting Content Inside a <div> Element with Other Elements

<div htp-get="/api/fetch-data">
    <div>other Elements</div>
    <div htp-data="">
        <!-- dynamic content -->
    </div>
</div>

Example 3: Inserting Content Inside a <p> Element

<div htp-get="/api/fetch-data" htp-t="p"></div>

<p>
    <!-- dynamic content -->
</p>

or

<div htp-get="/api/fetch-data" htp-t="p"></div>

<p htp-data="">
    <!-- dynamic content -->
</p>

or

<div htp-get="/api/fetch-data" htp-t="p"></div>

<p>
<div htp-data="">
 <!-- dynamic content -->
</div>

</p>

Usage Notes:

These examples demonstrate how htp-data can be used to specify the location where fetched content should be inserted in the HTML document after an AJAX request.

htp-swap

The htp-swap attribute in the $htp library specifies the property to be updated with the fetched content after a successful AJAX request. It determines how the fetched data will be integrated into the target element. Here's a breakdown of its usage:

Available Options:

  1. innerHTML:
    - Replaces the entire content inside the target element with the fetched data.

  2. append:
    - Appends the fetched data to the existing content inside the target element.

  3. after:
    - Inserts the fetched data immediately after the target element.

  4. before:
    - Inserts the fetched data immediately before the target element.

Example Usage:

<!-- Replaces the entire content inside the target element -->
<div htp-get="/api/fetch-data" htp-swap="innerHTML"></div>

<!-- Appends the fetched data to the existing content inside the target element -->
<div htp-get="/api/fetch-data" htp-swap="append"></div>

<!-- Inserts the fetched data immediately after the target element -->
<div htp-get="/api/fetch-data" htp-swap="after"></div>

<!-- Inserts the fetched data immediately before the target element -->
<div htp-get="/api/fetch-data" htp-swap="before"></div>
  1. prepend:
    - Inserts the fetched data at the beginning of the existing content inside the target element.

  2. textContent:
    - Sets the text content of the target element to the fetched data. This option is useful when you want to replace only the text content without affecting the HTML structure.

Example Usage:

<!-- Inserts the fetched data at the beginning of the existing content -->
<div htp-get="/api/fetch-data" htp-swap="prepend"></div>

<!-- Sets the text content of the target element to the fetched data -->
<div htp-get="/api/fetch-data" htp-swap="textContent"></div>

Usage Notes:

This explanation outlines the usage of htp-swap in the $htp library, allowing you to control how fetched data is integrated into the target element after an AJAX request.

htp-swap-s

In this example, let's say you have an external HTML file called example.html containing some HTML content and scripts. You want to fetch this content and insert it into your current HTML document before a specific target element, while also adjusting the scripts behavior.

External HTML File (example.html):

<h1>Heading....</h1>
<script>
    // JavaScript code
</script>
<script src="/some.js"></script>

Integration into Current HTML Document:

<div htp-get="/example.html" htp-swap-s="before"> 
    <!-- This will fetch the content of 'example.html' and insert it before the current element -->
    <script>
        // JavaScript code
    </script>
    <script src="/some.js"></script>
    <!-- data before fetch scripts -->
    <div htp-data>
        <!-- Placeholder for dynamic content -->
        <!-- <h1>Heading....</h1> -->
    </div>
</div>

Explanation:

This example demonstrates how to fetch content from an external HTML file and adjust script behavior during insertion using the htp-swap-s attribute, providing flexibility in managing dynamic content integration in your web application.

htp-s

In this example, we'll demonstrate how to use the htp-s attribute to specify a callback function to handle the success of an AJAX request.

HTML Markup:

<div htp-get="/api/fetch-data" htp-s="calling">
    <div htp-data>
        <!-- Placeholder for fetched data -->
    </div>
</div>

JavaScript Callback Function:

<script>
    // Define the callback function to handle the success of the AJAX request
    function calling(element, status) {
        // `element` parameter represents the element that triggered the AJAX request
        // `status` parameter represents the status of the AJAX request

        // Your logic here to handle the success status
        console.log("AJAX request successful!");
        console.log("Element: ", element);
        console.log("Status: ", status);
    }
</script>

Explanation:

This example demonstrates how to use the htp-s attribute to define a callback function that executes upon successful completion of an AJAX request triggered by the $htp library.

htp-sync

In this example, we'll demonstrate how to use the htp-sync attribute to control the synchronization behavior of HTTP requests triggered by $htp.

HTML Markup:

<div class="load-more-cnt" htp-get="/load-more.php" htp-query='{"key":1,"id":"$id"}' htp-sync="true" htp-swap="append">
    <div class="cnt" htp-data="">
        <p data="1">first paragraph</p>
        <p data="2">second paragraph</p>
    </div>
    <button>load more</button>
</div>

JavaScript:

<script>
    // Event listener for the "load more" button
    var button = document.querySelector("button");
    button.addEventListener("click", function() {
        // Get the last paragraph's data attribute value
        var id = Array.from(document.querySelectorAll('p')).slice(-1)[0].getAttribute("data");

        // Trigger the AJAX request with the updated id value
        $htp.call(document.querySelector(".load-more-cnt"), {id: id});
    });
</script>

Explanation:

This example demonstrates how to use the htp-sync attribute to ensure that AJAX requests triggered by $htp are synchronized, preventing concurrent execution and ensuring that requests are processed in the expected order.

Loading Dynamically

In this example, we'll demonstrate how to dynamically load content from an external URL using $htp. We'll also handle loading indicators and error messages.

CSS Styling:

<style>
    /* Display loading indicator when htp-on attribute is present */
    .target[htp-on] {
        /* Style for when loading */
    }

    /* Hide dynamic content and error message by default */
    .target[htp-on] .dynamic,
    .target[htp-fail] .dynamic {
        display: none;
    }

    .page-error {
        display: none;
    }

    /* Display error message if loading fails */
    .target[htp-fail] .page-error {
        display: block;
    }

    /* Hide loading indicator when loading is done or fails */
    .target[htp-done] .loading, 
    .target[htp-fail] .loading {
        display: none;
    }
</style>

HTML Markup:

<!-- Using htp-get directly -->
<div class="target" htp-get="/home.html">
    <div class="loading" loader="icon"></div>
    <div class="page-error" style="color: var(--error-color)">
        Page Can't Load. Please Try Again!!!
    </div>
    <div class="dynamic" htp-data="">
        <!-- Placeholder for dynamic content -->
    </div>
</div>

<!-- Using htp-t to specify target -->
<div htp-get="/home.html" htp-t=".target"></div>

<div class="target">
    <div class="loading" loader="icon"></div>
    <div class="page-error" style="color: var(--error-color)">
        Page Can't Load. Please Try Again!!!
    </div>
    <div class="dynamic" htp-data="">
        <!-- Placeholder for dynamic content -->
    </div>
</div>

Explanation:

This example demonstrates how to use $htp to load content dynamically from an external URL while providing feedback to users through loading indicators and error messages.

htp-ldr

In this example, we'll demonstrate how to load content dynamically with a loader indicator while providing error handling.

CSS Styling:

<style>
    /* Hide dynamic content by default */
    .dynamic-t {
        background: pink;
        display: none;
    }

    /* Show dynamic content when loading is done */
    .dynamic-t[htp-done] {
        display: block;
    }

    /* Hide loading indicator and error message when loading is done */
    .target[htp-done] .loading, 
    .target[htp-fail] .loading {
        display: none;
    }

    /* Show error message if loading fails */
    .target[htp-fail] .page-error {
        display: block;
    }
</style>

HTML Markup:

<div 
    htp-get="/home.html"
    htp-t=".dynamic-t"
    htp-ldr=".target"
></div>

<div class="target">
    <div class="loading" loader="icon"></div>
    <div class="page-error" style="color: var(--error-color)">
        Page Can't Load. Please Try Again!!!
    </div>
</div>

<div class="dynamic-t">
    <div class="dynamic" htp-data="">
        <!-- Placeholder for dynamic content -->
    </div> 
</div>

Explanation:

htp-type

In this example, we'll demonstrate how to use progress indicators for download and upload operations.

Download Progress:

<div class="target" htp-get="/home.html">
    <!-- Progress indicator for download -->
    <progress class="loading" value="0" max="100" htp-type="progress">0%</progress>

    <!-- Error message for failed download -->
    <div class="page-error" style="color: var(--error-color)">
        Page Can't Load. Please Try Again!!!
    </div>

    <!-- Placeholder for dynamic content -->
    <div class="dynamic" htp-data="">
        <!-- dynamic content -->
    </div>
</div>

Upload Progress:

<div class="target" htp-get="/post.py" htp-query='{"key":1,"id":"20"}'>
    <!-- Progress indicator for upload -->
    <progress class="loading" value="0" max="100" htp-type="progress-up">0%</progress>

    <!-- Error message for failed upload -->
    <div class="page-error" style="color: var(--error-color)">
        Page Can't Load. Please Try Again!!!
    </div>

    <!-- Placeholder for dynamic content -->
    <div class="dynamic" htp-data="">
        <!-- dynamic content -->
    </div>
</div>

Explanation:

htp-type and htp-type-t

In this example, we'll demonstrate how to use a progress indicator with custom styling for a download operation.

<div class="target" htp-get="/home.html">
    <!-- Custom progress indicator with width-based style -->
    <div class="loading progress" htp-type="progress" htp-type-t="width" style="width: 0%;"></div>

    <!-- Error message for failed download -->
    <div class="page-error" style="color: var(--error-color)">
        Page Can't Load. Please Try Again!!!
    </div>

    <!-- Placeholder for dynamic content -->
    <div class="dynamic" htp-data="">
        <!-- dynamic content -->
    </div>   
</div>

Explanation:

Cross-Origin Note

When using AJAX requests, it's essential to be aware of cross-origin restrictions imposed by web browsers. These restrictions are in place to enhance security and prevent malicious attacks.

Same-Origin Policy:

Cross-Origin Resource Sharing (CORS):

Handling Cross-Origin Issues:

JSONP (JSON with Padding):

Conclusion:

Understanding and addressing cross-origin issues is crucial for building robust and secure web applications. By ensuring proper CORS configuration and handling, you can facilitate seamless communication between your client-side JavaScript code and server-side resources while maintaining a high level of security.