FetchIt β€” Submit Forms Without Reloading

Fetch API Extras

FetchIt is a modern, lightweight component for MODX Revolution designed for submitting and processing forms using the native Fetch API. It replaces legacy solutions (like AjaxForm), enabling forms to work without page reloads and without relying on heavy libraries like jQuery.

Why choose FetchIt?

  • No dependencies. The component runs on pure JavaScript. You don’t need to include jQuery, which speeds up site loading and improves PageSpeed.
  • Lightweight. The script weighs only ~5 KB and is included with the defer attribute, without blocking page rendering.
  • Flexibility. Easily integrates with any CSS frameworks (Bootstrap, Tailwind) and JS notification libraries (Notyf, SweetAlert2).
  • Easy migration. The functionality is very similar to AjaxForm + FormIt, making the transition intuitive.

Installation

FetchIt is available for free installation via the “Package Installer” in the MODX admin panel. Main sources:

Quick Start

Running the form requires just two steps: preparing the HTML markup (chunk) and calling the snippet on the page.

1. Creating a form chunk

Create a chunk (for example, tpl.MyForm) with the following markup. Please note the following important attributes:

  • Fields (input, textarea) must have a name attribute.
  • The submit button must have type="submit".
  • To display validation errors, use spans with the data-error="field_name" attribute.
<form action="[[~[[*id]]]]" method="post">
    <div class="form-group">
        <label for="name">Имя:</label>
        <input type="text" name="name" id="name" value="[[+fi.name]]" class="form-control" required>
        <!-- Бюда FetchIt вставит тСкст ошибки ΠΏΡ€ΠΈ Π²Π°Π»ΠΈΠ΄Π°Ρ†ΠΈΠΈ -->
        <span class="error" data-error="name">[[+fi.error.name]]</span>
    </div>

    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" value="[[+fi.email]]" class="form-control" required>
        <span class="error" data-error="email">[[+fi.error.email]]</span>
    </div>

    <div class="form-group">
        <label for="message">Π‘ΠΎΠΎΠ±Ρ‰Π΅Π½ΠΈΠ΅:</label>
        <textarea name="message" id="message" class="form-control" required>[[+fi.message]]</textarea>
        <span class="error" data-error="message">[[+fi.error.message]]</span>
    </div>

    <button type="submit" class="btn btn-primary">ΠžΡ‚ΠΏΡ€Π°Π²ΠΈΡ‚ΡŒ</button>
    
    <!-- БообщСния ΠΎΠ± успСхС/ошибкС (ΠΎΠΏΡ†ΠΈΠΎΠ½Π°Π»ΡŒΠ½ΠΎ) -->
    [[+fi.success:is=`1`:then=`<div class="alert alert-success">[[+fi.successMessage]]</div>`]]
    [[+fi.validation_error:is=`1`:then=`<div class="alert alert-danger">[[+fi.validationErrorMessage]]</div>`]]
</form>

2. Calling the Snippet

Place a call to FetchIt on the page where the form should be. Inside FetchIt, we call the standard FormIt for email processing and validation.

Important! The snippet must be called uncached (with the exclamation point [[!FetchIt]]).

[[!FetchIt?
    &snippet=`FormIt`
    &form=`tpl.MyForm`
    &hooks=`email`
    &emailSubject=`НовоС сообщСниС с сайта`
    &emailTo=`info@mysite.com`
    &validate=`name:required,email:required:email,message:required`
    &validationErrorMessage=`ΠŸΠΎΠΆΠ°Π»ΡƒΠΉΡΡ‚Π°, ΠΈΡΠΏΡ€Π°Π²ΡŒΡ‚Π΅ ошибки Π² Ρ„ΠΎΡ€ΠΌΠ΅!`
    &successMessage=`Бпасибо! Π’Π°ΡˆΠ΅ сообщСниС ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ ΠΎΡ‚ΠΏΡ€Π°Π²Π»Π΅Π½ΠΎ.`
]]

Snippet Parameters

FetchIt accepts its own parameters to customize frontend behavior, and passes all unknown parameters to the snippet handler (FormIt by default).

Parameter Default Description
&form tpl.FetchIt.example Name of the chunk with the form’s HTML code.
&snippet FormIt Name of the snippet that will process data on the server (validation, hooks).
&actionUrl [[+assetsUrl]]action.php Connector URL for sending requests. Typically no changes are required.
&clearFieldsOnSuccess 1 Clear form fields after successful submission (1 – Yes, 0 – No).
&hooks, &validate, etc. β€” Any FormIt parameters (or your custom snippet).

JavaScript API and Events

FetchIt provides a powerful API for interacting with a form on the client. You can intercept the submission process, modify data, or display custom notifications.

Main Events

  • fetchit:before β€” Fires before submitting. A great place for additional JavaScript validation or adding data to FormData.
  • fetchit:success β€” Fires upon a successful response from the server (success: true).
  • fetchit:error β€” Fires upon an error (validation failed or a server error).

Example 1: Adding data before submitting

document.addEventListener('fetchit:before', (e) => {
    const { form, formData } = e.detail;
    // ДобавляСм ΠΏΡ€ΠΎΠΈΠ·Π²ΠΎΠ»ΡŒΠ½ΠΎΠ΅ ΠΏΠΎΠ»Π΅, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ³ΠΎ Π½Π΅Ρ‚ Π² вСрсткС
    formData.append('page_title', document.title);
    console.log('Π€ΠΎΡ€ΠΌΠ° отправляСтся...');
});

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ 2: Π’ΡΠΏΠ»Ρ‹Π²Π°ΡŽΡ‰ΠΈΠ΅ увСдомлСния (Notyf)

FetchIt “ΠΈΠ· ΠΊΠΎΡ€ΠΎΠ±ΠΊΠΈ” Π½Π΅ навязываСт стили ΡƒΠ²Π΅Π΄ΠΎΠΌΠ»Π΅Π½ΠΈΠΉ. Π’Ρ‹ ΠΌΠΎΠΆΠ΅Ρ‚Π΅ ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡ΠΈΡ‚ΡŒ Π»ΡŽΠ±ΡƒΡŽ Π±ΠΈΠ±Π»ΠΈΠΎΡ‚Π΅ΠΊΡƒ, Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€, Notyf.

// ΠŸΠΎΠ΄ΠΊΠ»ΡŽΡ‡ΠΈΡ‚Π΅ JS ΠΈ CSS Π±ΠΈΠ±Π»ΠΈΠΎΡ‚Π΅ΠΊΠΈ Notyf Π² шаблонС Π·Π°Ρ€Π°Π½Π΅Π΅
const notyf = new Notyf();

document.addEventListener('fetchit:success', (e) => {
    const { response } = e.detail;
    // response.message ΠΏΡ€ΠΈΡ…ΠΎΠ΄ΠΈΡ‚ ΠΈΠ· ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Π° &successMessage
    notyf.success(response.message || 'Π€ΠΎΡ€ΠΌΠ° ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ ΠΎΡ‚ΠΏΡ€Π°Π²Π»Π΅Π½Π°!');
});

document.addEventListener('fetchit:error', (e) => {
    const { response } = e.detail;
    // response.message содСрТит &validationErrorMessage ΠΈΠ»ΠΈ ΠΎΡˆΠΈΠ±ΠΊΡƒ Ρ…ΡƒΠΊΠ°
    notyf.error(response.message || 'ΠŸΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»Π° ошибка.');
});

Processing with a Custom Snippet

If you need to process data more complex than FormIt allows, you can specify your snippet in the &snippet parameter. The $FetchIt object is available within it for returning standardized responses.

Call:

[[!FetchIt?
    &form=`myForm`
    &snippet=`myCustomHandler`
]]

Π‘Π½ΠΈΠΏΠΏΠ΅Ρ‚ myCustomHandler:

<?php
// Fetching data
$name = $_POST['name'] ?? '';

// Basic validation
if (empty($name)) {
// Returning an error. The second argument is an array of field errors to highlight.
return $FetchIt->error('Validation error', [
'name' => 'The name field is required'
]);
}

// Some logic (writing to the database, API request...)

// Returning success
return $FetchIt->success('Everything went fine!', [
'custom_data' => 'Some data for JS'
]);

Working with files

FetchIt automatically handles file uploads. You don’t need to manually assemble the FormData object or specify specific headersβ€”the component will do it automatically.

To send attachments:

  1. Add the enctype="multipart/form-data" attribute to the form tag.
  2. Add the <input type="file" name="attachment"> field.
  3. In the snippet call, don’t forget to specify the attachment hook, for example, the standard email (FormIt will automatically process the files and attach them to the email if the field name matches the settings).
<form action="[[~[[*id]]]]" method="post" enctype="multipart/form-data">
<!-- Other fields --> 
<div class="form-group"> 
<label>Attach file:</label> 
<input type="file" name="file" class="form-control-file"> 
</div> 
<button type="submit">Submit</button>
</form>

Migrating from AjaxForm

If you’re used to using AjaxForm, switching to FetchIt will be painless. The main differences concern JavaScript events.

Functionality AjaxForm (jQuery) FetchIt (Vanilla JS)
Before-submit event af_complete (partial) fetchit:before
Success event af_complete (with status check) fetchit:success
Event Errors af_complete (with status check) fetchit:error
Form Reset Parameter &frontend_reset Parameter &clearFieldsOnSuccess

Example: Integration with SweetAlert2

You can use beautiful modal windows instead of the standard alert() or Notyf. Example of connecting SweetAlert2:

// Handling a successful submission
document.addEventListener('fetchit:success', (e) => {
const { response } = e.detail;

Swal.fire({
title: 'Great!',
text: response.message,
icon: 'success',
confirmButtonText: 'Close'
});
});

// Error Handling
document.addEventListener('fetchit:error', (e) => {
const { response } = e.detail;

Swal.fire({
title: 'Error!',
text: response.message || 'Check that the fields are filled in correctly',
icon: 'error',
confirmButtonText: 'OK'
});
});

Conclusion

FetchIt is the “gold standard” for forms in modern MODX. It frees your site from legacy jQuery, speeds up page load times, and gives the developer full control over the data submission process via a convenient JS API.

Use it for contact forms, callback forms, calculators, and any other interactive elements where speed and flexibility are important.

Rate article
MODX 3
Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.