2

I need to submit a form, using SproutForms, via AJAX, so i can get the response and then show some "gated" content on the page. The content (i.e. PDF link, etc) is tied to a particular entry page, so i'd like to stay on that page and not doing a normal POST to a generic success page. I can't find any info on the SproutForms plugin page on how to do this, just that it's supported (noted in the change log). Please help

5

I figured it out (edited with my FORM mark-up as well):

I'm actually rendering the FORM using the SproutForms method:

<div class="submit-via-ajax">
    {{ craft.sproutForms.displayForm(block.gatedContentForm.first().handle) }}
</div>

and then my JS looks for any form submissions from a ".submit-via-ajax" block

// process the form
$('.submit-via-ajax form').submit(function(event) {

    // get the form data
    var formData = $(this).serialize();

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'sproutForms/entries/saveEntry', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
        encode          : true
    })
        // using the done promise callback
        .done(function(data) {

            // here we will handle errors and validation messages
            if (data.success == true)
            {
                // show/hide content/elements
            }
            else
            {
                // show an error
            }
    });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});
  • Glad you figured it out. We'll consider adding an example to the docs. As you've shown here, the general principles of submitting Sprout Forms over ajax are the same as any other form you'd submit over ajax, we aren't doing anything fancy there and Sprout Forms will give you back a response in json to work with as necessary. – Ben Parizek Apr 25 '16 at 17:48
  • carbonjoetunis, would you be willing to share your Form code, as I am attempting the same (just Ajax submission at this stage) but having some troubles. – Nutmeg Oct 18 '16 at 6:07
  • edited the original post to include how i'm rendering the FORM mark-up. – carbonjoetunis Oct 25 '16 at 15:52

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.