Straightforward interactive HTTP requests from within your Alpine.JS markup

Overview

Alpine Fetch

GitHub file size in bytes

Straightforward interactive HTTP requests from within your Alpine.JS markup.

View the live demo here

What does this do?

Alpine.JS is a rugged, minimal tool for composing behavior directly in your markup. It can be used, even by those with little experience in Javascript, to add interactivity to web pages.

Alpine Fetch is a magic helper for Alpine.JS which makes it easy to do HTTP requests within markup.

Native Alpine approach to HTTP requests

One area where Alpine does require you to go outside markup is when making HTTP requests to dynamically populate parts of the page.

Someone looking to make a call on an API endpoint, might need to do something like the following:

<div x-data="{
        result: null,
        async retrieveData() { 
            this.result = await (await fetch('/endpoint')).text(); 
        }
     }" 
     x-init="retrieveData()"
>
     <span x-text="result"></span>
</div>

... which is quite verbose, and involves promises which are not straightforward for beginners.

Alpine Fetch

Alpine Fetch adds magic functions to abstract a lot of this away and makes it much more straightforward to populate your page via HTTP requests. The above example using Alpine Fetch would be:

<div x-data>
    <span x-text="await $fetch('/endpoint)"></span>
</div>

Alpine Fetch can fetch simple text from the server using the $fetch method or it can fetch and parse JSON using the $fetchjson method.

It supports all HTTP methods such as GET and POST and PUT.

It has no dependencies other than Alpine.

Installation

Include the following <script> tag in the <head> of your document, before Alpine:

<script defer src="https://gitcdn.link/cdn/hankhank10/alpine-fetch/main/alpine-fetch.js"></script>

Usage

At its most basic $fetch accepts a URL and returns the contents of that URL.

Unlike the generic Javascript fetch method which requires dealing with promises, this simply waits for the response to be received and then returns it.

$fetch should be preceded by await to ensure that this happens.

String to x-text

The most basic example is to fetch a string from the server and populate it in your markup via the x-text method of alpine.

<div x-data>
    <span x-text="await $fetch('https://weathermockapi.herokuapp.com/hello_world')"></span>
</div>

HTML to x-html

The $fetch helper can be used anywhere, so if you don't want to render it as text you can pass it to the x-html method of Alpine - or to a class, or any other part of the markup. It behaves like any other variable.

<div x-data>
    <span x-html="await $fetch('https://weathermockapi.herokuapp.com/hello_world_html')"></span>
</div>

Retrieving once, using multiple times

You might want to use the same data in multiple places in your markup. In that case, it would make sense to just fetch it once and use it multiple times. You can do this by retrieving it into the x-data tag like any other variable.

<div x-data="{ hello_world: await $fetch('https://weathermockapi.herokuapp.com/hello_world' }">
    <span x-text="hello_world"></span>
    <span x-text="hello_world"></span>
</div>

Retrieving JSON

$fetch retrieves data which it expects to be text, but you can also use $fetchjson to retrieve data which is JSON and then render the relevant part of that into your page.

<div x-data>
    <span x-text="await $fetchjson('https://weathermockapi.herokuapp.com/some_json', jsonItem='weather')"></span>
</div>

Specifying a method

$fetch and $fetchjson assume that you want to use a GET method but you can specify that you want to send another.

<span x-text="await $fetch('/post_url', method='POST')"></span>
<span x-text="await $fetch('/delete_url', method='DELETE')"></span>

Responding to actions

If you specify a DOM element or a variable to be equal to $fetch or $fetchjson then the methods will automatically fetch on init.

However you can also customise when they do the fetch however you like. In the below example, it will fetch only when the user clicks the button.

<div x-data="{ weather: 'uncertain at this stage' }">

    The weather is <span x-text="weather"></span>
    
    <button
            x-on:click="weather = await $fetchjson('https://weathermockapi.herokuapp.com/some_json', jsonItem='weather')"
    >Click me to change the weather</button>

</div>

Examples

You can view all of these examples in the examples/examples.html file in this repo or a live demo here.

Contributing

I very much welcome comments, suggestions and contributions.

If you notice issues please open an issue on Github.

If you have improvements or suggestions please submit a pull request.

You might also like...

A WebApp to preview FTML, the SCP Foundation's markup language, on the Web.

A WebApp to preview FTML, the SCP Foundation's markup language, on the Web.

Wikitext Previewer (FTML/Wikidot Web Previewer) A WebApp to preview FTML, the SCP Foundation's markup language, on the Web. "SCP-173" by Moto42, from

Jun 4, 2022

⏱ Simple Alpine.js plugin to display the human-readable distance between a date and now.

⏱ Alpine TimeAgo ⏱ An Alpine.js plugin to return the distance between a given date and now in words (like "3 months ago", "about 2 hours ago" or "in a

Dec 22, 2022

A clean integration between Cleave.js and Alpine. ✨

✨ Help support the maintenance of this package by sponsoring me. Alpine Mask This packages provide a custom x-mask directive and $mask magic variable,

Dec 26, 2022

↕️ A little Alpine.js plugin to automatically resize a textarea to fit its content.

↕️ Alpine Autosize ↕️ A little Alpine.js plugin to automatically resize a textarea to fit its content. 🚀 Installation CDN Include the following scri

Nov 5, 2022

A simple library for handling keyboard shortcuts with Alpine.js.

✨ Help support the maintenance of this package by sponsoring me. Alpine.js Mousetrap A simple library for handling keyboard shortcuts with Alpine.js.

Nov 14, 2022

IntelliSense for Alpine.js

IntelliSense for Alpine.js

IntelliSense for Alpine.js Features Provides syntax highlighting for Alpine.js directives along with autocomplete for all base directives and modifier

Nov 17, 2022

E-commerce website using Laravel, Tailwindcss and Alpine.js

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Dec 12, 2022

Multi-step wizard helpers for Alpine.js

Multi-step wizard helpers for Alpine.js

Alpine Wizard This package provides an Alpine directive (x-wizard) and a magic helper ($wizard) that allow you to quickly build multi-step wizards usi

Dec 23, 2022

📦 Alpine JS plugin to extend the functionality of the official $persist plugin

Alpine JS Persist Extended Alpine JS magic method $storage extends the official $persist plugin to help you work with local storage 📦 Example 👀 div

Dec 28, 2022
Comments
  • Possible to post x-data with a response body and headers?

    Possible to post x-data with a response body and headers?

    Hi, nice project! Is it possible to post x-data with this plugin? I looked through the JS and it doesn't look like it, but thought I'd ask.

    I'm trying to submit form elements that are binded to x-data values. And I'd like to send the x-data using a request body, due to the size of the text. It would also be nice to customize the headers, but not required for my current issue.

    opened by kartzke 0
Owner
null
Quickly create an interactive HTML mock-up by auto sourcing lorem ipsum/images generators, with minimal html markup, and no server side code

RoughDraft.js v0.1.5 Quickly mockup / prototype HTML pages with auto-generated content, without additional JavaScript or server side code. <section>

Nick Dreckshage 464 Dec 21, 2022
A set of APIs for handling HTTP and HTTPS requests with Deno 🐿️ 🦕

oak commons A set of APIs that are common to HTTP/HTTPS servers. HTTP Methods (/method.ts) A set of APIs for dealing with HTTP methods. Content Negoti

oak 7 May 23, 2022
nodejs load balancing app to distribute http requests evenly across multiple servers.

load-balancer-nodejs nodejs load balancing app to distribute http requests evenly across multiple servers. How to use ? Please edit the file 'config.j

Abdi Syahputra Harahap 13 Nov 7, 2022
Browser asynchronous http requests

It's AJAX All over again. Includes support for xmlHttpRequest, JSONP, CORS, and CommonJS Promises A. It is also isomorphic allowing you to require('re

Dustin Diaz 2.9k Dec 20, 2022
📡Usagi-http-interaction: A library for interacting with Http Interaction API

?? - A library for interacting with Http Interaction API (API for receiving interactions.)

Rabbit House Corp 3 Oct 24, 2022
Add focal point alignment of images to your Alpine 3.x components with a custom directive.

Alpine Focal Add focal point alignment of images to your Alpine 3.x components with a custom directive. This package only supports Alpine v3.x. About

Michael Lefrancois 2 Oct 12, 2021
Animate your Alpine components.

Animate your Alpine components ?? This package provides you with a simple helper to animate your ALpine.js components. Installation The recommended wa

Ralph J. Smit 18 Nov 16, 2022
Adds a handy $parent magic property to your Alpine components.

✨ Help support the maintenance of this package by sponsoring me. Alpine $parent Access parent components using a handy $parent magic variable. This pa

Ryan Chandler 10 Aug 29, 2022
Typed HyperText Markup Language

Typed HyperText Markup Language You can add types to the HyperText Markup Language. Types To declare two types, they must be separated by a period and

TypeMarkup 1 Jan 22, 2022
This is a To-Do List. It shows a minimalist design with the next features: Add new tasks, edit tasks, markup completed tasks, and erase all completed tasks. Built with JavaScript.

Project Name To Do List Built With HTML CSS JavaScript Live Demo To do List Live Demo Link Getting Started This is a To Do List. It shows a minimalist

Santiago Cárdenas 6 Jun 9, 2022