Forms

HTML element <form> serializes user input data and to sumbits it to new server url specified in the action attribute. Then browser triggers full page reload with the new url. Library modifies this behavior to prevent a white flash. Request to server is made using Fetch API, and response body replaces the current document without a full page reload.

In some cases regular <form> behavior is not modified:

Methods from the list above can be used in markup. When you need to keep regular <form> behavior in JavaScript - call method Event#preventDefault inside your submit event handler for an appropriate element.

Event flow

  1. A <form> element triggers native submit event in browser
  2. Library prevents default behavior, serializes the form and dispatches ajaxify:serialize event with the user input
  3. If ajaxify:serialize wasn't prevented triggers ajaxify:fetch event and starts AJAX request
  4. When the AJAX request ends library dispatches ajaxify:load event with the response object
  5. If ajaxify:load wasn't prevented triggers ajaxify:render event and updates content of the <body> element

Take a look at the Custom Events section to read about dispatched events in more details.

ajaxify:serialize

In plain HTML it's not possible to change user data that will be submitted to server by a <form> element. Thats why library introduces additional custom event ajaxify:serialize. For this event CustomEvent#detail contains FormData object that is going to be sent to server.

You can create an event handler for ajaxify:serialize and modify CustomEvent#detail before it will be submitted to server:

const formEl = document.getElementById("#myForm");

formEl.addEventListener("ajaxify:serialize" function(e) {
    const formData = e.detail;
    // adds extra property "foo" to the request body
    formData.append("foo", "bar");
    // modifies value for a key
    formData.set("key", "new value");
}, false);