Submit Shopify Contact Form Using AJAX
Shopify’s default contact form submits via traditional page reload. By using AJAX, we can send the form data asynchronously while keeping the user on the same page.
1. Create a Contact Form in page.contact.liquid
Add the following form in page.contact.liquid
or inside a section:
<form id="contact-form" class="contact-form"> <input type="text" name="contact[name]" placeholder="Your Name" required> <input type="email" name="contact[email]" placeholder="Your Email" required> <textarea name="contact[body]" placeholder="Your Message" required></textarea> <button type="submit">Send Message</button> <p id="form-response"></p> </form>
2. JavaScript for AJAX Form Submission
Place this script in theme.js
or inside a <script>
tag in page.contact.liquid
.
document.addEventListener("DOMContentLoaded", function () { const contactForm = document.getElementById("contact-form"); contactForm.addEventListener("submit", function (event) { event.preventDefault(); // Prevent page reload let formData = new FormData(contactForm); fetch(contactForm.action, { method: "POST", body: formData, }) .then(response => response.text()) .then(data => { if (data.includes("form-success")) { document.getElementById("form-response").innerHTML = "Thank you! Your message has been sent."; contactForm.reset(); // Reset form after successful submission } else { document.getElementById("form-response").innerHTML = "Oops! Something went wrong."; } }) .catch(error => { console.error("Error:", error); document.getElementById("form-response").innerHTML = "An error occurred. Please try again."; }); }); });
3. Explanation of Code
- Prevents the default form submission to avoid a page reload.
- Uses
fetch()
to send form data asynchronously to Shopify’s default contact form handler. - Checks for success messages by detecting Shopify’s
form-success
class in the response. - Displays a success or error message based on the response.
- Resets the form after successful submission.