### Install Dependencies Source: https://github.com/imacrayon/alpine-ajax/blob/main/README.md Run this command in the cloned repository to install project dependencies. ```bash npm install ``` -------------------------------- ### Mock Server Setup and Route Definition Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/reference/creating-demos.md Include the mock server script and define a route to handle POST requests to '/update-quantity'. This example demonstrates how to mock a server response using HTML, which will be used by Alpine AJAX for frontend updates. ```html 0
``` -------------------------------- ### Install Alpine AJAX via NPM Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/reference/installation.md Install the package using npm. Then, import and initialize Alpine AJAX within your JavaScript bundle. ```bash npm i @imacrayon/alpine-ajax ``` ```javascript import Alpine from 'alpinejs' import ajax from '@imacrayon/alpine-ajax' window.Alpine = Alpine Alpine.plugin(ajax) ``` -------------------------------- ### Server-Side Mock Logic Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/progress-bar.md A module script simulating server routes and job management logic for the progress bar example. ```javascript ``` -------------------------------- ### Install and Configure Morph Plugin via NPM Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/reference/x-merge.md Install the package via npm and register the plugins with Alpine. ```bash npm i @alpinejs/morph ``` ```js import Alpine from 'alpinejs' import morph from '@alpinejs/morph' import ajax from '@imacrayon/alpine-ajax' window.Alpine = Alpine Alpine.plugin(morph) Alpine.plugin(ajax) ``` -------------------------------- ### Install Alpine AJAX via CDN or NPM Source: https://context7.com/imacrayon/alpine-ajax/llms.txt Load the plugin before the Alpine.js core. Ensure the correct order of script tags or module imports. ```html ``` ```javascript // Via NPM import Alpine from 'alpinejs' import ajax from '@imacrayon/alpine-ajax' window.Alpine = Alpine Alpine.plugin(ajax) Alpine.start() ``` -------------------------------- ### Install Morph Plugin via CDN Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/reference/x-merge.md Include the Morph plugin script before the Alpine AJAX script to enable morphing capabilities. ```html ``` -------------------------------- ### Alpine.js Routing and AJAX Setup Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/lazy-load.md Configures window routing for '/posts' and '/posts/1' endpoints. The '/posts/1' route simulates a 2-second delay before resolving with post content. Includes a call to `window.example('/posts')`. ```javascript window.route('GET', '/posts', () => dashboard()) window.route('GET', '/posts/1', () => new Promise(resolve => { setTimeout(() => resolve(post()), 2000) })) window.example('/posts') function dashboard() { return `

Refresh the page to watch this post lazy load into view:

` } function post() { return `

Finn Mertins

I'll fly the paper, as an airplane, down the bedroom ladder. It'll triple barrel-roll past the kitchen, open the fridge, and cook some eggs; then eat the eggs and unfold itself as it lays on the carpet in front of Marceline's door.

``` -------------------------------- ### Common $ajax patterns Source: https://context7.com/imacrayon/alpine-ajax/llms.txt Examples of using $ajax for inline validation, lazy loading, infinite scrolling, and full configuration options. ```html
Loading...
Click to load
``` -------------------------------- ### View default and custom request headers Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/reference/x-headers.md Example of the headers sent by the form, including default Alpine AJAX headers and the custom header. ```txt X-Alpine-Request: true X-Alpine-Target: comments comments_count Custom-Header: Shmow-zow! ``` -------------------------------- ### Initialize AJAX Job Form Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/progress-bar.md The initial form used to trigger a POST request to start a background job. ```html

New Job

``` -------------------------------- ### Watch for Changes Source: https://github.com/imacrayon/alpine-ajax/blob/main/README.md Starts a watcher that rebuilds the library automatically upon detecting file changes. ```bash npm run watch ``` -------------------------------- ### JavaScript Mock Server and View Logic Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/bulk-update.md Provides a mock database and routing logic to handle GET and PUT requests for contact status updates. ```javascript ``` -------------------------------- ### JavaScript Routing and View Logic Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/notifications.md Sets up server routes for handling GET and POST requests to '/action'. It manages a counter for notifications and dynamically generates the view, including the form and the notification list. ```javascript var count = 0; window.route('GET', '/action', () => view()) window.route('POST', '/action', () => { count++ return view() }) window.example('/action') function view() { return `
` } function notification() { return `
  • The button was clicked ${count} ${count > 1 ? 'times' : 'time'}.
  • ` } ``` -------------------------------- ### Initial Form Markup Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/inline-validation.md The starting HTML structure for the form with an email field configured to trigger an AJAX request on change. ```html
    ``` -------------------------------- ### AJAX lifecycle events Source: https://context7.com/imacrayon/alpine-ajax/llms.txt Examples of handling request lifecycle events for confirmation, loading states, success/error handling, and request modification. ```html
    ``` -------------------------------- ### JavaScript Mock API and Routing Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/dialog-form.md Implements a simple in-memory database and routes for handling contact data. It defines GET and PUT routes for listing, editing, and updating contacts. ```javascript var database = function () { let data = [ { id: 1, name: "Finn Mertins", email: "fmertins@candykingdom.gov", status: "Active" }, { id: 2, name: "Jake the Dog", email: "jake@candykingdom.gov", status: "Active" }, { id: 3, name: "BMO", email: "bmo@mo.co", status: "Active" }, { id: 4, name: "Marceline", email: "marceline@vampirequeen.me", status: "Inactive" } ] return { find: (id) => data.find(contact => contact.id === parseInt(id)), update: (id, changes) => { let index = data.findIndex(contact => contact.id === parseInt(id)) if (index !== -1) { data[index] = Object.assign(data[index], changes) } }, all: () => data, } }() window.route('GET', '/contacts', () => index(database.all())) database.all().forEach(contact => { window.route('GET', `/contacts/${contact.id}/edit`, () => edit(database.find(contact.id))) window.route('PUT', `/contacts/${contact.id}`, (input) => { database.update(contact.id, input) return edit(database.find(contact.id), 'contact:updated') }) }) window.example('/contacts') function index(contacts) { let rows = contacts.map(contact => ` ${contact.name} ${contact.status} ${contact.email} Edit `).join('\n') return table(rows) } function edit(contact, event = '') { return `
    ${serverEvent(event)}
    ``` -------------------------------- ### Table Row Example Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/dialog-form.md Represents a single row in the contacts table, including a link to edit the contact details. ```html Finn Mertins Active fmertins@candykingdom.gov Edit ``` -------------------------------- ### Server-Side Routing and Data Generation (JavaScript) Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/infinite-scroll.md Defines a GET route for '/contacts' that simulates fetching paginated data with a delay. It generates mock contact records and constructs the HTML for the table and pagination. ```javascript window.route('GET', '/contacts', (input) => { if (input.page) { return new Promise(resolve => { setTimeout(() => resolve(view(parseInt(input.page))), 1000) }) } return view(1) }) window.example('/contacts') function view(page) { let max = 5 let end = page * 10 let cursor = end - 9 let rows = [] let prefix = '' let status = '' while (cursor <= end) { prefix = getPrefix(cursor) status = Math.random() < 0.5 ? 'Active' : 'Inactive' rows.push(` ${prefix}MO ${prefix.toLowerCase()}mo@mo.co ${status} `) cursor++; } rows = rows.join('\n') let prev = '' let next = '' if (page > 1) { prev = ` Prev` } if (page < 5) { next = `Next` } let intersect = next ? `x-intersect="$ajax('/contacts?page=${page + 1}', { target: 'records pagination' })"` : '' return ` ${rows}
    Name Email Status
    ` } let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' function getPrefix(number, result = ''){ let index = number % alphabet.length let quotient = number / alphabet.length if (index - 1 == -1) { index = alphabet.length quotient = quotient - 1 } result = alphabet.charAt(index - 1) + result return quotient >= 1 ? getPrefix(parseInt(quotient), result) : result } ``` -------------------------------- ### Inline Validation Demo Logic Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/inline-validation.md JavaScript module defining the routes and view rendering logic for the inline validation example. ```javascript window.route('GET', '/register', () => view()) window.route('POST', '/validate-email', (input) => { if (input.email === 'test@example.com') { return view() } else if (input.email.includes('@')) { return view('The email is already taken.') } return view('The email field is invalid.') }) window.example('/register') function view(message = '') { message = message ? `
    ${message}
    ` : '' return `
    ${message}
    ` } ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/imacrayon/alpine-ajax/blob/main/README.md Locally serves the documentation site built with Eleventy. It automatically bundles the latest Alpine AJAX build. ```bash npm run start ``` -------------------------------- ### Build Library Source: https://github.com/imacrayon/alpine-ajax/blob/main/README.md Executes the build process to create a fresh version of the library in the /dist directory. ```bash npm run build ``` -------------------------------- ### Configure Global Defaults Source: https://context7.com/imacrayon/alpine-ajax/llms.txt Set global headers and merge strategies during Alpine initialization. ```javascript import Alpine from 'alpinejs' import ajax from '@imacrayon/alpine-ajax' Alpine.plugin(ajax.configure({ // Default headers for all requests headers: { 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }, // Default merge strategy: 'replace', 'morph', 'append', etc. mergeStrategy: 'morph' })) Alpine.start() ``` -------------------------------- ### POST /validate-email with $ajax Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/reference/ajax.md Example of using the $ajax helper to send a POST request with a JSON body for email validation. ```APIDOC ## POST /validate-email ### Description This endpoint is used for server-side email validation. It accepts an email address in the request body and returns validation results. ### Method POST ### Endpoint /validate-email ### Request Body - **email** (string) - Required - The email address to validate. ### Request Example ```json { "email": "user@example.com" } ``` ### Response #### Success Response (200) - **valid** (boolean) - Indicates if the email is valid. - **message** (string) - Optional - A message providing details about the validation result. #### Response Example ```json { "valid": true } ``` ``` -------------------------------- ### Implement Demo Logic Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/inline-edit.md JavaScript module defining routes and rendering functions for the inline edit demo. ```javascript let contact = { "first_name": "Finn", "last_name": "Mertens", "email": "fmertens@candykingdom.gov" } window.route('GET', '/contacts/1', () => show(contact)) window.route('GET', '/contacts/1/edit', () => edit(contact)) window.route('PUT', '/contacts/1', (input) => { contact.first_name = input.first_name contact.last_name = input.last_name contact.email = input.email return show(contact) }) window.example('/contacts/1') function edit(contact) { return `
    Cancel
    ` } function show(contact) { return `

    First Name: ${contact.first_name}

    Last Name: ${contact.last_name}

    Email: ${contact.email}

    Edit
    ` } ``` -------------------------------- ### Configure Alpine AJAX Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/reference/configuration.md Explains how to set global configuration options for the Alpine AJAX plugin using the configure method. ```APIDOC ## Configuration ### Description Configure the default behavior of Alpine AJAX when importing it into your project. ### Method Alpine.plugin(ajax.configure(options)) ### Parameters #### Options - **headers** (object) - Optional - Additional request headers, as key/value pairs, included in every AJAX request. Default: {} - **mergeStrategy** (string) - Optional - Set the default merge strategy used when new content is merged onto the page. Default: 'replace' ### Request Example ```js import ajax from '@imacrayon/alpine-ajax' Alpine.plugin(ajax.configure({ headers: { 'X-CSRF-Token': 'mathmatical!' }, mergeStrategy: 'morph' })) ``` ``` -------------------------------- ### HTML Structure for Dialog and Links Source: https://github.com/imacrayon/alpine-ajax/blob/main/docs/examples/dialog.md Sets up an unordered list of links that trigger a dialog and the dialog element itself. The dialog opens when a 'dialog:open' event is dispatched. ```html