Web Forms with File Uploads Without Reloading the Page (Ajax in Practice)

They are essential for functional websites and can very quickly become the biggest source of frustration for users: we’re talking about web forms. To make web forms easier and more convenient for users, a few simple adjustments can offer some practical benefits.

Headerbild mit einem Screenshot eins Webformulares
Reading duration: approx. 3 Minutes

The new design of the fully responsive LeasePlan website called for multiple web forms on a single page. However, since forms typically cause the entire page to reload when submitted, adjustments were necessary. Reloading the entire page when submitting a form not only causes frustration due to the wait time. The amount of data transferred also plays a major role—especially given the growing number of mobile users.

Only the form should reload after submission

Users gain no benefit from having the entire page reload when they submit a form. It’s rather frustrating to stare at a blank white page after submitting and wonder what’s actually happening.

How do users benefit from this adjustment? It’s simple:

  • There is less data transfer, since only the form data is sent to the server, and the server’s response is smaller, since at most only the form needs to be sent back to the client. This is particularly useful for mobile users, since not everyone has an unlimited data plan or always has the best reception.
  • After submitting the form, users aren’t taken back to the top of the page, since the page isn’t reloaded.
  • It is possible to reload the page without the browser attempting to resubmit the form, since the page continues to be accessed via GET and the POST request to the server occurs only via Ajax.
  • When using multiple web forms on a content-rich page, they can be submitted one after another. If users wish to edit multiple web forms simultaneously, the data already entered in another form is not lost after submitting one web form.

Technically, this can be solved quite easily by submitting the form via Ajax. This ensures that only the entered form data is sent to the server. Consequently, the server’s response no longer needs to be the entire page, but only the form’s response. Of course, this can vary greatly depending on the requirements. In the event of an error, a clear error message should appear, and the form should highlight the fields that were filled out incorrectly. Upon successful submission, a success message should appear accordingly.

Example of Implementing File Upload Using Ajax

Form Structure:

<form name="name-des-formulars" method="post" enctype="multipart/form-data">
    <div>
        <label for="name">Name</label>
        <input type="text" id="name" name="name-des-formulars[name]">
    </div>
 
    <div>
        <label for="document">Dokument</label>
        <input type="file" id="document" name="name-des-formulars[document]">
    </div>
 
    <!-- weitere Felder -->
 
    <div>
        <button value="submit" type="submit" onclick="yourJavaScriptFunction(clickEvent);" name="name-des-formulars[submit]">Absenden</button>
    </div>
</form>

Important

To upload a file, set the "enctype" attribute in the form to "multipart/form-data."

Excerpt from the JavaScript:

function yourJavaScriptFunction(clickEvent) {
    clickEvent.preventDefault();
  
    // Initialisierung weiterer Variablen
  
    var formPostData = new FormData(document.forms.namedItem('name-des-formulars'));
 
 
    jQuery.ajax({
        type: "post",
        url: requestURL,
        data: formPostData,
        dataType: "json",
        contentType: false,
        cache: false,
        processData: false,
        //...

For file uploads, we use theFormDataobject here, since otherwise the files will not be sent along with the request. In addition, the `contentType` and `processData` settings must be set to `false` for this purpose, since different formats (text, images, documents, etc.) are being transferred here. Furthermore, caching should not be enabled, as this involves individual user-specific data that cannot be cached.


How can this be implemented in TYPO3 using FormHandler?

Here at punkt.de, we use the Formhandler extension for web forms, among other tools, because it’s easy to customize and extend and offers a wide range of functionality. To submit Formhandler forms via Ajax, only a few adjustments are necessary:

First, we need our own `AjaxFileUploadHandler` that inherits from `Tx_Formhandler_AjaxHandler_JQuery`. This is necessary because we want to pass the data via the `FormData` object to enable file uploads via Ajax, and this feature is not yet configurable through Formhandler.

class Tx_PtFormhandler_AjaxFileUploadHandler_JQuery extends Tx_Formhandler_AjaxHandler_Jquery
{
    public function initAjax()
    {
        // der Code dieser Funktion aus der Eltern-Klasse sollte hier entsprechend dem obigen Beispiel angepasst werden
    }

Important

While using your own AjaxHandler gives you full control over the code without having to patch the extension, you should compare the parent class with your own AjaxHandler during updates to prevent potential issues caused by code changes.

Next, the corresponding form needs to be converted to Ajax:

ajax {
   class = Tx_PtFormhandler_AjaxFileUploadHandler_JQuery
   config {
      jsPosition = footer
      ajaxSubmit = 1
      ajaxSubmitCallback = formhandlerCallbackOnAjaxSubmit
      submitButtonSelector = #my-form-id
   }
}

In this configuration, there are a few important aspects to consider regarding the use of Ajax:

  • jsPosition: Depending on how and where the jQuery library is included, it is important to position the form handler’s inline JavaScript correctly.
  • ajaxSubmitCallback: If the form contains JavaScript code that manipulates the content of the web form—such as a custom file upload—the ajaxSubmitCallback can be used to re-execute an initialization function for such code, since, in the event of errors, the form is re-rendered and the page’s JavaScript code is not re-executed. The called function must, of course, be available throughout the entire page.
  • submitButtonSelector: When using multiple WebForms on a single page, a submit button must be defined for them; otherwise, the automatically generated JavaScript code will no longer target the correct form.

With these few adjustments to web forms, you can optimize performance, load time, usability, and traffic (for both the client and the server). It’s an investment that pays off for both website operators and website visitors.

Share:

More articles

Jeder Einzelne ist ein Tropfen, gemeinsam sind wir ein Meer.
Rebecca Düker, Product Owner at punkt.de
Working at punkt.de