Ajax Contact form

Highlighted
New Member
4 0 0

I tried implementing the AJAX handler from Yunieski_DG, but when I redirect to the URL "/challenge#form_id" I'm getting a 404 page. 

Any ideas? Thank you!

0 Likes
Highlighted
Tourist
5 0 1

Hi @pkavanaghjr could you make sure you are passing the proper form id?

0 Likes
Highlighted
New Member
4 0 0

Hey @Yunieski_DG 

I ended up making it work by allowing the window to redirect by default instead of forcing the JS `window.location` change.

Here's what my function looks like:

/**
 * AJAX Submit Shopify Contact Forms 
 *
 * @param {array} contact_forms - array of form elements to add submit event listeners too
 */
function ajaxForms_contact(contact_forms){
    // Allow the passing of forms array, default to all .contact-form elements
    contact_forms = typeof contact_forms !== 'undefined' ? contact_forms : $('.contact-form').toArray();

    // Loop forms and add event listener
    $.each(contact_forms, function(i, form) {
        var formData = {
            form: $(this),
            formId: $(this).attr('id'),
            action: $(this).attr('action'),
            successMsg: "<p class='note note--success'>Thanks for contacting us. We'll get back to you as soon as possible.</p>"
        };
        
        // Add submit event listener
        $(formData.form).on('submit', function (e) {
            // Init AJAX
            $.ajax({
                type: 'POST',
                async: true,
                url: formData.action,
                data: formData.form.serialize(),
                beforeSend: function() {
                    formData.form.addClass('sending'); 
                },
                error: function(data) {
                    console.log('error: ',data);
                    formData.form.addClass('error');
                    
                    // 429 error - too many requests
                    if(data.status == 429) {
                        // Allow for default redirect to challenge form, do not force
                        console.log('Allow default window redirection for challenge');
                    }else {
                        e.preventDefault(); // if fields are empty, paste errors 
                        $(formData.form).before("<div class='errors'>" + response.statusText + "</div>");
                    }
                },
                success: function (data) {
                    e.preventDefault(); // prevent default if successful and challenge is not needed
                    console.log('success: ',data);
                    formData.form.addClass('success');
                    formData.form.fadeOut(300, function(){
                        formData.form.closest('div').append(formData.successMsg);
                    });
                }
            }); // close ajax
        }); // close 'submit' event
    }); // close loop
}

// Init function
ajaxForms_contact();

 

0 Likes