Skip to content

Instantly share code, notes, and snippets.

@samhernandez
Last active October 20, 2022 07:45
Show Gist options
  • Save samhernandez/cf046e387c1f2fb95f744f1c152cb0a3 to your computer and use it in GitHub Desktop.
Save samhernandez/cf046e387c1f2fb95f744f1c152cb0a3 to your computer and use it in GitHub Desktop.
Craft Contact Form with Axios
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Contact Form Plugin Example with Axios</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
</head>
<body>
<!--
Assumes that you're using the Pixel & Tonic Contact Form plugin
-->
<form id="my-form" method="post" action="" accept-charset="UTF-8">
<h3><label for="from-name">Your Name</label></h3>
<input id="from-name" type="text" name="fromName" value="">
<h3><label for="from-email">Your Email</label></h3>
<input id="from-email" type="email" name="fromEmail" value="">
<h3><label for="subject">Subject</label></h3>
<input id="subject" type="text" name="subject" value="">
<h3><label for="message">Message</label></h3>
<textarea rows="10" cols="40" id="message" name="message"></textarea>
<input type="submit" value="Send">
</form>
<script>
window.Craft = {
csrfTokenValue: "{{ craft.app.request.getCsrfToken()|e('js') }}",
csrfTokenName: "{{ craft.app.config.general.csrfTokenName|e('js') }}",
};
const formElement = document.getElementById("my-form");
formElement.onsubmit = function(e) {
e.preventDefault();
let formData = new FormData(formElement);
formData.append('action', 'contact-form/send');
formData.append(Craft.csrfTokenName, Craft.csrfTokenValue);
axios.post('/', formData, {
headers: {
'X-CSRF-Token': Craft.csrfTokenValue,
'Content-Type': 'application/json'
}
}).then(response => {
console.log(response)
}).catch(error => {
console.warn(error);
})
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment