Web forms with file upload 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 are talking about web forms. In order to make the use of web forms easier and more convenient for the user, a few adjustments can bring some practical advantages for the user.

Reading duration: approx. 4 Minutes

The new design of the fully-responsive LeasePlan website provided for several web forms on one page. However, since forms normally cause the entire page to be reloaded when they are submitted, adjustments were necessary. Loading the entire page when submitting a form not only causes frustration due to the waiting time. In view of the increasing number of mobile users, the amount of data transferred also plays a major role.

Only the form should be reloaded after submission

The user has no advantage if the entire page is reloaded when the form is submitted. It is rather frustrating to stare at a blank white page after submitting and wonder what is happening.

How does the user benefit from such a customization? Quite simply:

  • There is less data transfer, as only the form data is sent to the server, and the response from the server is less, as at most only the form has to be resent to the client. This is particularly useful for users of mobile devices, as not everyone has an unlimited flat rate or always has the best reception.
  • The user does not end up back at the top of the page after submitting, as there is no reloading.
  • It is possible to reload the page without the browser wanting to resubmit the form, as the page is still called up via GET and the POST to the server only takes place via Ajax.
  • If several web forms are used on a content-rich page, they can be sent one after the other. If a user wants to edit several web forms at the same time, the data already entered in another form is not lost after submitting a web form.

Technically, this can be solved quite easily by sending the form via Ajax. This means that only the form data entered is sent to the server. This means that the server no longer needs the complete page as a response, but only the response from the form. This can of course vary greatly depending on the requirements. In the event of an error, a meaningful error message should of course appear and the form should be highlighted with the corresponding incorrectly filled fields. If the form is sent successfully, a success message should appear accordingly.


Example of an implementation of the file upload via Ajax

Structure of the form:

<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

For the file upload, the "enctype" property in the form must be set 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 the file upload, we use the FormData object here, as otherwise the files are not sent. In addition, the contentType and processData settings must be set to false for this, as different formats (text, images, documents, etc.) are transferred here. Caching should also not be activated, as this involves individual user-specific data that cannot be cached.


How can the whole thing be realized in TYPO3 with form handlers?

At punkt.de, we use the Formhandler extension for web forms, among others, as it is easy to customize and extend and offers a lot of functionality. Only a few adjustments are necessary to send formhandler forms via Ajax:

First, we need our own AjaxFileUploadHandler that inherits from Tx_Formhandler_AjaxHandler_JQuery. This is necessary because we want to transfer the data via the FormData object in order to receive a file upload via Ajax and this is not yet configurable via form handlers.

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

By using your own AjaxHandler, you have free control over the code without having to patch the extension, but you should compare the parent class with your own AjaxHandler during updates to prevent possible problems caused by code changes.

The next step is to convert the corresponding form to Ajax:

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

In this configuration, there are some important aspects to consider in connection with the use of Ajax:

  • jsPosition: depending on how or where the jQuery library is integrated, it is important to position the form handler inline JavaScript accordingly.
  • ajaxSubmitCallback: if there is JavaScript code in the form that manipulates the content of the web forms, e.g. a separate file upload, the ajaxSubmitCallback can be used to re-execute an initialization function for such code, as the form is rendered again in the event of errors and the JavaScript code of the page is not re-executed. The called function must of course be available on the entire page.
  • submitButtonSelector: if several web forms are used on one page, a submit button must be defined above them, as otherwise the automatically generated JavaScript code will no longer take the correct form into account.

With these few adjustments to web forms, performance, loading time, usability and traffic (for both client and server) can be optimized. An investment that pays off for website operators and website visitors.

Share:

More articles

Teamgeist
Sandra Wilke, Marketing / Vertrieb at punkt.de
Working at punkt.de