enigmadigital / Formerly

Plugin to allow users to create custom forms within Craft CMS
MIT License
59 stars 24 forks source link

Not working Sending Ajax? #84

Open paveell opened 7 years ago

paveell commented 7 years ago

Good day Tell me how to configure sending via Ajax? Connected the script but it does not work. thank you

webrgp commented 7 years ago

Hi @paveell ,

First check if your for is correct, but you can skip the "redirect" hidden input:

<form method="post" enctype="multipart/form-data"  accept-charset="utf-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="formerly/submissions/postSubmission">
    <input type="hidden" name="formId" value="{{ form.id }}">
    ...
    {# loop question like the exemple #}
    <div class="form-group">
        <label for="{{ question.handle }}">{{ question.instructions ? question.instructions : question.name }}</label>
        <input type="text" class="form-control" id="{{ question.handle }}"
            {% if question.required %}
                required
        aria-required="true"
        data-val-required="'{{ question.name }}' is required"
        data-val="true"
            {% endif %}
            {% if question.errorMessage %}
                data-validator-error-message="{{ question.errorMessage }}"
            {% endif %}
            {% if question.validationPattern %}
                pattern="{{ question.validationPattern }}"
            {% endif %}
            name="questions[{{ question.handle }}]"
            value="{{ submission is defined ? submission[question.handle] }}"
        >
        <span class="help-block"></span>
    </div>
    {# end loop #}
    ...
</form>
<div class="thank-you-message hidden">
...
</div>

So, the idea is to:

  1. Intercept the submit event of the form
  2. Post it using ajax
  3. Process errors and success

Then, your javascript (using jQuery + Bootstrap) should look something like this:


$('form').on('submit', function(event){
    var $form = $(this);
    // Reset validation states to the fields
    $form.find(".form-group").removeClass('has-error');
    $form.find(".help-block").text('');

    $.ajax({
        url : '',
        method: 'POST',
        data: $form.serialize(),
        success: function(response, textStatus, jqXHR) {
            if ( response.ok === "no") {
                for (var fieldError in response.errors) {
                    if (response.errors.hasOwnProperty(fieldError)) {
                        $('#' + fieldError).parent('.form-group').addClass('has-error');
                        $('#' + fieldError).next('.help-block').text( response.errors[fieldError] );
                    }
                }
            } else {
                $form.next('.thank-you-message').removeClass('hidden');
                $form.remove();
           }
        },
        error: function(jqXHR, textStatus, errorThrown){
            // process errors other than the actual submission
        }
});

I hope it helps ;-)