Express Forms Express Forms for Craft
2.x Discontinued

WARNING

The Express Forms plugin has been discontinued. Please see the Freeform migration guide for more information.


Submitting a form using AJAX

You can check out the AJAX example inside the Demo templates included with Express Forms. Below is an example from it.

TIP

For no-fuss AJAX control built right into your forms, you may want to consider Freeform.

Place something like the following at your page footer:

<script>
  var safari = navigator.userAgent.indexOf('Safari') > -1;

  function ajaxifyForm(event) {
    var form = event.target;
    var data = new FormData(form);
    var request = new XMLHttpRequest();

    if (safari) {
      for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].type == 'file') {
          if (form.elements[i].value == '') {
            var elem = form.elements[i];
            data.delete(elem.name);
          }
        }
      }
    }

    var method = form.getAttribute('method');
    var action = form.getAttribute('action');

    request.open(method, action ? action : window.location.href, true);
    request.setRequestHeader('Cache-Control', 'no-cache');
    request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    request.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
    request.onload = function () {
      removeMessages(form);

      if (request.status === 200) {
        var response = JSON.parse(request.response);

        if (response.success) {
          // Reset the form so that the user may enter fresh information
          form.reset();

          // ============================================================
          // Uncomment this to have the form redirect to the success page
          // ============================================================
          // if (response.return) {
          //   window.location.href = response.return;
          // }

          renderFormSuccess(form);
        } else if (response.errors || response.formErrors) {
          renderErrors(response.errors, form);
          renderFormErrors(response.formErrors, form);
        }

        replaceInputs(form, response);
        unlockSubmit(form);
      } else {
        console.error(request);
      }

      unlockSubmit(form);
    };

    request.send(data);
    event.preventDefault();
  }

  function replaceInputs(form, response) {
    if (response.duplicateCheck) {
      var prefix = response.duplicateCheck.prefix;
      var value = response.duplicateCheck.value;
      var input = form.querySelector('input[name^="' + prefix + '"]');
      if (input) {
        input.setAttribute('name', value);
        input.setAttribute('value', value);
      }
    }
  }

  /**
   * Remove the "disabled" state of the submit button upon successful submit
   *
   * @property form
   */
  function unlockSubmit(form) {
    form.querySelector('button[type=submit]').removeAttribute('disabled');
    if (typeof grecaptcha !== 'undefined') {
      grecaptcha.reset();
    }
  }

  function removeMessages(form) {
    // Remove error messages
    form.querySelectorAll('ul.errors').remove();
    var fieldsWithErrors = form.querySelectorAll('.has-error');
    for (
      var fieldIndex = 0;
      fieldIndex < fieldsWithErrors.length;
      fieldIndex++
    ) {
      fieldsWithErrors[fieldIndex].classList.remove('has-error');
    }

    // Remove success messages
    form.querySelectorAll('.form-success').remove();
    document.getElementsByClassName('form-errors').remove();
  }

  function renderFormSuccess(form) {
    var successMessage = document.createElement('div');
    successMessage.classList.add('alert', 'alert-success', 'form-success');

    successMessage.appendChild(
      document.createTextNode('Form has been submitted successfully!')
    );

    form.insertBefore(successMessage, form.childNodes[0]);
  }

  function renderErrors(errors, form) {
    for (var key in errors) {
      if (!errors.hasOwnProperty(key) || !key) {
        continue;
      }

      var messages = errors[key];
      var errorsList = document.createElement('ul');
      errorsList.classList.add('errors');

      for (
        var messageIndex = 0;
        messageIndex < messages.length;
        messageIndex++
      ) {
        var message = messages[messageIndex];
        var listItem = document.createElement('li');
        listItem.appendChild(document.createTextNode(message));
        errorsList.appendChild(listItem);
      }

      var inputList = form.querySelectorAll(
        '*[name=' + key + "], *[name='" + key + "[]']"
      );
      for (var inputIndex = 0; inputIndex < inputList.length; inputIndex++) {
        var input = inputList[inputIndex];

        input.findAncestor('form-group').classList.add('has-error');
        input.findAncestor('form-group').appendChild(errorsList);
      }
    }
  }

  function renderFormErrors(errors, form) {
    var errorBlock = document.createElement('div');
    errorBlock.classList.add('alert', 'alert-danger', 'form-errors');

    errorBlock.appendChild(
      document.createTextNode(
        'Error! Please review the form and try submitting again.'
      )
    );

    if (errors.length) {
      var errorsList = document.createElement('ul');
      for (var messageIndex = 0; messageIndex < errors.length; messageIndex++) {
        var message = errors[messageIndex];
        var listItem = document.createElement('li');

        listItem.appendChild(document.createTextNode(message));
        errorsList.appendChild(listItem);
      }

      errorBlock.appendChild(errorsList);
    }

    form.insertBefore(errorBlock, form.childNodes[0]);
  }

  // Add remove prototypes
  Element.prototype.remove = function () {
    this.parentElement.removeChild(this);
  };

  Element.prototype.findAncestor = function (className) {
    let el = this;
    while (!el.classList.contains(className)) {
      el = el.parentElement;
    }

    return el;
  };

  NodeList.prototype.remove = HTMLCollection.prototype.remove = function () {
    for (var i = this.length - 1; i >= 0; i--) {
      if (this[i] && this[i].parentElement) {
        this[i].parentElement.removeChild(this[i]);
      }
    }
  };

  document.getElementById('ajax-form').addEventListener('submit', ajaxifyForm);
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197

And be sure to assign a matching ID attribute to your form (e.g. ajax-form is used above) to the form.openTag():

{{ form.openTag({
    return: '?success=1',
    attributes: {
        id: "ajax-form",
    },
}) }}
1
2
3
4
5
6