hyTags
HomeHome DocumentationDocumentation

Request and Response Handling

Overview

This example demonstrates making an HTTP request and inserting the response into the page. Click the button to fetch user information from the server. The user info is generated from the User-Agent and Accept-Language headers.
<button>Load user info</button>
<on click>
  <request-new url="/demo/user-info" method="get">
  <!-- Async network call -->
  <request-send>
  <response-is-error>
  <if-true>
    <!-- Error handling -->
    <selection-set-text text="Try again">
    <function-return>
  </if-true>
  <selection-scope next-sibling=".result">
    <!-- Insert response content -->
    <response-get-fragment>
    <selection-replace-children>
  </selection-scope>
</on>

<div class="result"></div>
👆 Try to change something! ⚠️ Preview only available on larger screens

Explanation

  • request-new: Creates a new HTTP request to the specified URL. Pushes a request onto the stack.
  • request-send: Takes the request from the stack and sends it asynchronously. Code after this line waits for the response. Pushes the response onto the stack.
  • response-is-error: Takes the response from the stack and checks if the request failed, pushing a bool onto the stack.
  • if-true: Takes the bool from the stack and executes its body if true.
  • selection-scope: Temporarily changes the selection to execute commands on a different element (the result container).
  • response-get-fragment: Takes the response from the stack (still available) and extracts the HTML fragment, pushing it onto the stack.
  • selection-replace-children: Takes the fragment from the stack and inserts it into the current selection.
Test succeeded Test failed