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:
- when a
<form>has non-emptytargetattribute; - when a
<form>has non-http(s)url as theactionattribute value (tel:,mailto:etc.).
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
- A
<form>element triggers nativesubmitevent in browser - Library prevents default behavior, serializes the form and dispatches
ajaxify:serializeevent with the user input - If
ajaxify:serializewasn't prevented triggersajaxify:fetchevent and starts AJAX request - When the AJAX request ends library dispatches
ajaxify:loadevent with the response object - If
ajaxify:loadwasn't prevented triggersajaxify:renderevent 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);