Skip to content

Instantly share code, notes, and snippets.

@jasonvarga
Last active September 5, 2021 23:34
Show Gist options
  • Save jasonvarga/e1c241c108e3dcf8c324 to your computer and use it in GitHub Desktop.
Save jasonvarga/e1c241c108e3dcf8c324 to your computer and use it in GitHub Desktop.
Using Statamic HTML Caching with a dynamic Raven form. Put the form on a separate page and pull it in via JS.
<!--
A template for raven stuff.
Display this at a URL like /contact-form for example
Exclude this URL from html_caching
Make this form look/act like it was part of the parent page.
The contents of #raven will be injected into it.
-->
<div id="raven">
{{ if {raven:success} }}
...
{{ /if }}
{{ if {raven:has_errors} }}
...
{{ /if }}
{{ raven:form }}
...
{{ /raven:form }}
</div>
// When the DOM is ready
$(function(){
// Cache the element
var formDiv = $('#contact-form');
// Set the URL the form lives on
var ravenURL = '/contact-form';
// Perform an ajax request to the form page
var req = $.ajax({
url: ravenURL
});
// When the request is done...
req.done(function(data){
// Get the contents of the #raven div
var ravenHtml = $(data).find('#raven').html();
// and put it inside the #contact-form div
formDiv.html(ravenHtml);
});
// Hijack the form submission
formDiv.on('submit', 'form', function(e){
var form = $(this);
// Don't submit the form
e.preventDefault();
// Submit it via ajax instead
var req = $.ajax({
url: ravenURL,
data: form.serialize()
});
// When the request is done...
req.done(function(data){
// Get the contents of the #raven div
var ravenHtml = $(data).find('#raven').html();
// and put it inside the #contact-form div
formDiv.html(ravenHtml);
});
});
});
enable: true
exclude: contact-form
<!--
The template where you want the form to be injected to.
For example, a contact page.
You *should* cache this page.
The form will be injected into the #contact-form div with
JavaScript, but without JS there will be a link to the
form template anyway.
-->
<h1>Contact</h1>
<div id="contact-form">
<a href="/contact-form">Send us a message using our form.</a>
</div>
<!-- Scripts should be placed in the appropriate place. -->
<script src="jquery.js"></script>
<script src="form.js"></script>
@Robert-Black
Copy link

Changing the ajax call to

var req = $.ajax({
      url: ravenURL,
      data: form.serialize(),
      type: 'POST'
});

Seems to do the trick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment