3

I am using Sprout Forms on a Craft 3 site and trying to submit my form via ajax.

I've been able to do this many times in Craft 2, but not having much luck with 3 (yet). The docs look mainly for Craft 2 - is there a better way to find examples for Craft 3?

Here is what the headers look like that I am sending:

CRAFT_CSRF_TOKEN: <huge string hash>
action: sprout-forms/entries/save-entry
redirect: <long redirect hash>
handle: contact
fields[fullName]: Damon
fields[email]: name@test.com
fields[phone]: 211-111-1111
fields[message]: Hello.

I am always getting a 302 response back - without any error or other indication of what might be missing. If I remove the handle field, I'll get a 400 error, so I know I'm hitting the correct method.

Status Code: 302 Found

Here is what my js looks like:

$.ajax({
    type: 'post',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    cache: false,
    data: $('#contact-form').serialize(),
    url: $('input[name=action]').val(),
    processData: false,
    dataType: 'json',
    timeout: 50000
}).done(function (response) {
    console.log(response);  // nothing.
}).fail(function (error) {
    // Total fail.
});

Here is what I am including in my form that is Craft/Sprout specific.

{{ csrfInput() }}
<input type="hidden" name="action" value="sprout-forms/entries/save-entry">
<input type="hidden" name="redirect" value="{{ form.redirectUri|hash }}">
<input type="hidden" name="handle" value="{{ form.handle }}">

Thank you for any suggestions!

2

First I want to say thank you to the support staff at Sprout for helping me figure out my error.

I have the default install settings/configuration for a Sprout form. Spam protection was enabled in my case and that's what was causing the 302.

If I want to have spam protection enabled, I need to have this inside my <form> tags:

{% hook 'sproutForms.modifyForm' %}

So my form looks like this now:

<form id="contact-form" method="post" class="main-form" accept-charset="utf-8">
    <fieldset>
        {% hook 'sproutForms.modifyForm' %}
        {{ csrfInput() }}
        <input type="hidden" name="action" value="sprout-forms/entries/save-entry">
        <input type="hidden" name="redirect" value="{{ form.redirectUri|hash }}">
        <input type="hidden" name="handle" value="{{ form.handle }}">
    </fieldset>

    <fieldset>
        {# Get the full name field. #}
        {% set fullName = form.getField('fullName') %}

        ...
    </fieldset>
</form>

I'm getting a 200 response back and the entry is getting created!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.