Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Autoajax Laravel Package

crudadmin/autoajax

AutoAjax by CrudAdmin brings automatic AJAX behavior to Laravel CRUD admin interfaces, enabling create, read, update, and delete actions to run without full page reloads for faster, smoother workflows with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Autoajax is a thin layer that intercepts native form submissions and turns them into fetch/XHR requests, then hands the JSON response back to your page. It is deliberately small, so "getting started" is mostly about wiring up three things: the asset, the form marker, and a JSON contract on the server.

1. Install. Expect a Composer package (for the Laravel service provider / asset publishing) plus a JS asset:

composer require crudadmin/autoajax
php artisan vendor:publish --provider="Crudadmin\Autoajax\AutoajaxServiceProvider"

If publishing registers a config file, open config/autoajax.php first — that is where endpoint, selector, and CSRF settings usually live. If the package is JS-only, skip the provider and copy dist/autoajax.js into your build.

2. Read the source before the README. With a package this small (low star count, zero dependents), the README is likely thin and the source is authoritative. Look at:

  • src/ or resources/js/ — the actual form interception logic (what selector/attribute it binds to, what it does with the response).
  • config/ — defaults for the form selector and the CSRF header name.
  • routes/ — if it ships any, otherwise you supply your own endpoints.

3. First use case — the classic "create" form. Start with a single form on a single page, not a whole CRUD suite:

<form action="{{ route('posts.store') }}" method="POST" data-autoajax>
    @csrf
    <input name="title" required>
    <textarea name="body"></textarea>
    <button type="submit">Save</button>
    <div data-autoajax-errors></div>
</form>

Verify the exact attribute/selector in the source — packages in this space use data-autoajax, data-ajax, or a JS initializer interchangeably.

Then make the controller speak JSON:

public function store(Request $request)
{
    $data = $request->validate([
        'title' => 'required|string|max:255',
        'body'  => 'required|string',
    ]);

    $post = Post::create($data);

    return response()->json([
        'ok'       => true,
        'message'  => 'Post created.',
        'redirect' => route('posts.index'),
    ]);
}

Once that one form works end-to-end (submit → no page reload → success message → redirect), you have the mental model for the rest of the package. Everything else is variations on the response contract.

Implementation Patterns

The response contract is the package

Autoajax doesn't decide what "success" means; your JSON does. Standardize on one shape across the app and handle it in one place:

{ "ok": true,  "message": "...", "redirect": "/posts", "html": "<tr>...</tr>" }
{ "ok": false, "errors": { "title": ["The title is required."] } }

Keep redirect, html, and message optional. A shared HandleAutoajaxResponse trait or a small JS callback (see extension points below) applied globally beats repeating branches in every controller.

Validation failures (422)

Laravel's ValidationException returns 422 with errors as JSON automatically when the request expects JSON. The one thing to check is that Autoajax sends Accept: application/json (or X-Requested-With: XMLHttpRequest) so $request->expectsJson() is true — otherwise you get an HTML redirect back to the form. If the package doesn't set it, add it in your form-submit interceptor or set the header explicitly.

Progressive enhancement pattern

Because Autoajax is an enhancement, write forms so they work without JS first: real action, method, @csrf, server-side validation with old() and $errors. Then layer Autoajax on top. This makes the package a convenience, not a load-bearing dependency — important for a package with a low maintenance signal.

The "modal edit" workflow

This is where the package earns its keep. Same form markup, reused for create and edit, loaded into a modal or slide-over:

  1. Click "Edit" → fetch the form partial into the container.
  2. Autoajax binds to the newly inserted form (verify it uses event delegation — see Gotchas).
  3. On success, close the modal and swap the row using the returned html payload.

Non-Laravel / plain PHP

The plain-PHP path is the same contract, minus the framework niceties. You supply:

  • A PHP endpoint that reads $_POST, validates, and json_encodes the response.
  • CSRF: either skip it or issue a token into a <meta name="csrf-token"> and have the package read it. If the package has no built-in CSRF handling, add it via the request-headers hook or by including _token in the form (Autoajax usually serializes all fields, so a hidden _token input "just works").
<?php
// store.php
header('Content-Type: application/json');
if (empty($_POST['title'])) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'errors' => ['title' => ['Title required']]]);
    exit;
}
// ... persist ...
echo json_encode(['ok' => true, 'redirect' => '/posts.php']);

Integration with your existing JS stack

If you're on Alpine/Livewire/Inertia, be explicit about ownership. Autoajax and Livewire both want to own the submit event; pick one per form. With Alpine, use Autoajax for plain HTML forms and Livewire for reactive ones — don't stack them on the same <form>.

Gotchas and Tips

CSRF is the #1 failure mode. Token rotation (session regeneration on login/logout) will 419 stale tokens. Read the token fresh from <meta name="csrf-token"> at submit time rather than capturing it on page load, and make sure Autoajax sends it as X-CSRF-TOKEN. In plain PHP, mirror this by echoing a token into a meta tag and refreshing it after any session change.

Redirects behave differently than you expect. If your controller returns a 302 redirect(), the browser fetch silently follows it and you get the destination HTML, not a signal to navigate. Always return {"redirect": "..."} (a 200) and let the JS perform location.href = .... Watch for this when reusing existing form-request controllers unchanged — they were written for full-page flow.

File uploads need FormData. If the package serializes fields with URLSearchParams, $_FILES will be empty. Check the source; if it doesn't branch on enctype="multipart/form-data", either patch the submit handler to build a FormData, or handle uploads in a separate non-Autoajax form. Do not set Content-Type manually when using FormData — let the browser add the boundary.

Event delegation for dynamic forms. Forms inside modals, tabs, or freshly-inserted HTML only work if the package binds at document level (submit delegation) rather than querying forms once at DOMContentLoaded. If it's the latter, call the re-init function after your modal renders — or wrap the submit handler yourself.

Double submits. Fast clicks can fire twice before the response returns. Disable the submit button and re-enable on completion/error, or guard on an in-flight flag. This bites hardest on slow endpoints and is easy to miss in local dev.

Debugging flow. Open DevTools → Network, filter to Fetch/XHR, submit, and inspect three things in order: (1) is the request even a fetch (not a document navigation)? (2) status code, (3) response body shape. If you get a full-page reload, the handler didn't attach (wrong selector or missing attribute). If you get HTML in the response, a ValidationException wasn't converted — check the Accept header. If you get 419, it's CSRF.

Error handling is likely minimal. Small packages often call response.json() without checking response.ok, so a 500 or 419 HTML response throws a confusing SyntaxError: Unexpected token <. Wrap the global handler: check response.ok and status 419, and fail loudly rather than silently.

Pinning and vendoring. Zero dependents and a low score means the maintenance bus factor is effectively one person. Pin an exact version in composer.json/package.json, commit the built JS asset if you can, and keep a one-paragraph note in your repo about what you rely on (selector + response contract) so you could fork or replace it in an afternoon. The package is small enough that "replace with 40 lines of fetch" is a legitimate fallback.

Extension points to rely on (in preference order): custom DOM events emitted before/after submit (hook these for analytics, button disabling, toasts), a configurable request-headers callback (for CSRF and Accept), and a configurable success/error callback. Prefer these over patching the source; if the package exposes none, wrap it — bind your own submit listener that calls preventDefault and does the fetch yourself, and treat Autoajax as reference code.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
diephp/sequences
users-au/socialite-provider
twidpay/twid-logger
mrnewport/laravel-plaid
mrnewport/laravel-repo
mrnewport/laravel-docsign
mrnewport/laravel-stow
mrnewport/laravel-flow
mrnewport/laravel-priceable
mrnewport/laravel-nestedterms
fredmeng/laravel-apidoc-generator
itstructure/laravel-multilingual-tools
pdustdar/elasticsearch
markupai/php-sdk
rlacerda83/lumem-microservice-shipment
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle