<p>If you want the error messages to be displayed identical to P&amp;T's template/macro default, this should do the trick:</p>

<pre><code>$(function(){
    $('#ajax-form').submit( function(ev) {

        // Prevent the form from actually submitting
        ev.preventDefault();

        // Remove any existing error messages from previous attempts
        $(this).find( '.errors' ).remove();

        // Get the post data
        var data = $(this).serialize();

        // Send it to the server
        $.post('/', data, function(response) {

            if (response.success) {

                // All good!
                $('#thanks').fadeIn();

            } else {

                // Loop through the errors and append to relevant fields
                for ( var fieldId in response.error ) {

                    // Create the &lt;ul&gt;
                    var $errors = $( '&lt;ul class="errors" /&gt;' );

                    // Wrap the error messages in &lt;li&gt; tags
                    var messages = $.map(response.error[fieldId], function(message){
                        return '&lt;li&gt;' + message + '&lt;/li&gt;';
                    });

                    // Append the error messages to the ul
                    $errors.append( messages.join( '' ) );

                    // Select the input element and append the .errors &lt;ul&gt; after it.
                    $('#'+fieldId).after($errors);

                }

            }
        });
    });
});
</code></pre>

<p>Just to be clear though, the PT Contact Form template doesn't force you to display your error messages in any given way; both the contact form template as a whole, and specifically how error messages are displayed (both the template macro for non-Ajax requests and the stuff in the <code>response.error</code> object) is obviously totally up to you.</p>

CC BY-SA 3.0
2015-03-18T23:19:56.687Z
2015-04-17T19:45:22.780Z
2015-04-17T19:45:22.780Z
Mats Mikkel Rummelhoff
<p>I'm trying out AJAX submission for the PT Contact Form for the first time. I've managed to get errors appearing on the frontend, but I don't feel like I'm doing it the right way. It also doens't integrated at all with the <code>{% macro errorList(errors) %}</code> code that comes with the form. This is my form JS:</p>

<pre><code>$(function(){
    $('#ajax-form').submit(function(ev) {
        // Prevent the form from actually submitting
        ev.preventDefault();

        // Get the post data
        var data = $(this).serialize();

        // Send it to the server
        $.post('/', data, function(response) {
            if (response.success) {
                $('#thanks').fadeIn();
            } else {
                // response.error will be an object containing any validation errors that occurred, indexed by field name
                // e.g. response.error.fromName =&gt; ['From Name is required']
                if (response.error.fromName) {$('ul.errors').append('&lt;li&gt;'+response.error.fromName+'&lt;/li&gt;');}
                if (response.error.fromEmail) {$('ul.errors').append('&lt;li&gt;'+response.error.fromEmail+'&lt;/li&gt;');}
                if (response.error.subject) {$('ul.errors').append('&lt;li&gt;'+response.error.subject+'&lt;/li&gt;');}
                if (response.error.message) {$('ul.errors').append('&lt;li&gt;'+response.error.message+'&lt;/li&gt;');}
            }
        });
    });
});
</code></pre>

<p>Form code:</p>

<pre><code>{% macro errorList(errors) %}
{% if errors %}
&lt;ul class="errors"&gt;
    {% for error in errors %}
    &lt;li&gt;{{ error }}&lt;/li&gt;
    {% endfor %}
&lt;/ul&gt;
{% endif %}
{% endmacro %}

{% from _self import errorList %}

&lt;form method="post" action="" accept-charset="UTF-8" id="ajax-form"&gt;
    {{ getCsrfInput() }}
    &lt;input type="hidden" name="action" value="contactForm/sendMessage"&gt;
    &lt;input type="hidden" name="redirect" value="/contact"&gt;

    &lt;label for="fromName"&gt;Name *&lt;/label&gt;
    &lt;input class="form-control" id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}"&gt;
    {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

    &lt;label for="fromEmail"&gt;Email *&lt;/label&gt;
    &lt;input class="form-control" id="fromEmail" type="text" name="fromEmail" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}"&gt;
    {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

    &lt;label for="subject"&gt;Subject&lt;/label&gt;
    &lt;input class="form-control" id="subject" type="text" name="subject" value="{% if message is defined %}{{ message.subject }}{% endif %}"&gt;
    {{ message is defined and message ? errorList(message.getErrors('subject')) }}

    &lt;label for="message"&gt;Message *&lt;/label&gt;
    &lt;textarea class="form-control" rows="10" cols="40" id="message" name="message"&gt;{% if message is defined %}{{ message.message }}{% endif %}&lt;/textarea&gt;
    {{ message is defined and message ? errorList(message.getErrors('message')) }}

    &lt;button type="submit" class="btn btn-primary"&gt;Submit&lt;/button&gt;
&lt;/form&gt;

&lt;ul class="my-errors"&gt;&lt;/ul&gt;
</code></pre>

<p>I've had to put a blank <code>&lt;ul class="my-errors"&gt;&lt;/ul&gt;</code> under my form, as the <code>.error</code> ul that comes with the contact form doesn't appear. Where am I going wrong?</p>

<p>Desired result: I get exactly the same error handling as I would if I wasn't submitting via AJAX - i.e., the error messages relating to specific fields appear under those fields in the form.</p>

<form><ajax><plugin-contactform>
How do you correctly handle errors using PT Contact Form when submitting via AJAX?
# How do you correctly handle errors using PT Contact Form when submitting via AJAX?

(Asked by: username_0 on 2015-03-18)

I'm trying out AJAX submission for the PT Contact Form for the first time. I've managed to get errors appearing on the frontend, but I don't feel like I'm doing it the right way. It also doens't integrated at all with the {% macro errorList(errors) %} code that comes with the form. This is my form JS:
$(function(){
    $('#ajax-form').submit(function(ev) {
        // Prevent the form from actually submitting
        ev.preventDefault();

        // Get the post data
        var data = $(this).serialize();

        // Send it to the server
        $.post('/', data, function(response) {
            if (response.success) {
                $('#thanks').fadeIn();
            } else {
                // response.error will be an object containing any validation errors that occurred, indexed by field name
                // e.g. response.error.fromName => ['From Name is required']
                if (response.error.fromName) {$('ul.errors').append(''+response.error.fromName+'');}
                if (response.error.fromEmail) {$('ul.errors').append(''+response.error.fromEmail+'');}
                if (response.error.subject) {$('ul.errors').append(''+response.error.subject+'');}
                if (response.error.message) {$('ul.errors').append(''+response.error.message+'');}
            }
        });
    });
});

Form code:
{% macro errorList(errors) %}
{% if errors %}

    {% for error in errors %}
    {{ error }}
    {% endfor %}

{% endif %}
{% endmacro %}

{% from _self import errorList %}


    {{ getCsrfInput() }}
    
    

    Name *
    
    {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

    Email *
    
    {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

    Subject
    
    {{ message is defined and message ? errorList(message.getErrors('subject')) }}

    Message *
    {% if message is defined %}{{ message.message }}{% endif %}
    {{ message is defined and message ? errorList(message.getErrors('message')) }}

    Submit




I've had to put a blank  under my form, as the .error ul that comes with the contact form doesn't appear. Where am I going wrong?
Desired result: I get exactly the same error handling as I would if I wasn't submitting via AJAX - i.e., the error messages relating to specific fields appear under those fields in the form.

**Tags:** form, ajax, plugin-contactform


---

## 1 answers

### Answer by username_1 on 2015-03-18. Score: 5 | Accepted answer

If you want the error messages to be displayed identical to P&T's template/macro default, this should do the trick:
$(function(){
    $('#ajax-form').submit( function(ev) {

        // Prevent the form from actually submitting
        ev.preventDefault();

        // Remove any existing error messages from previous attempts
        $(this).find( '.errors' ).remove();

        // Get the post data
        var data = $(this).serialize();

        // Send it to the server
        $.post('/', data, function(response) {

            if (response.success) {

                // All good!
                $('#thanks').fadeIn();

            } else {

                // Loop through the errors and append to relevant fields
                for ( var fieldId in response.error ) {

                    // Create the 
                    var $errors = $( '' );

                    // Wrap the error messages in  tags
                    var messages = $.map(response.error[fieldId], function(message){
                        return '' + message + '';
                    });

                    // Append the error messages to the ul
                    $errors.append( messages.join( '' ) );

                    // Select the input element and append the .errors  after it.
                    $('#'+fieldId).after($errors);

                }

            }
        });
    });
});

Just to be clear though, the PT Contact Form template doesn't force you to display your error messages in any given way; both the contact form template as a whole, and specifically how error messages are displayed (both the template macro for non-Ajax requests and the stuff in the response.error object) is obviously totally up to you.


---

