I am using Statamic Form and Antlers template with AJAX to submit a form. However the success variable is not longer working when the form is submitting so I am unable to update the text to show the form has been submitted.
{{ form:property_valuation id="propertyValuationForm" handle="property_valuation" x-data="formSetup()" x-on:submit.prevent="getResults($el)" }}
{{ if success }}
<div>
<p class="fw-bold text-white">
Thanks! We have received your request. We will reach out to you soon.
</p>
</div>
{{ else }}
{{ if errors }}
<div class="bg-danger text-white p-2">
{{ errors }}
{{ value }}<br>
{{ /errors }}
</div>
{{ /if }}
<div class="row row-cols-md-1 row-cols-lg-2 align-items-center gy-2">
<div>
<label for="field-email" class="visually-hidden">Email Address</label>
<input
type="email"
id="field-email"
name="email"
class="form-control text-black-50-placeholder py-2"
placeholder="Your email address"
>
</div>
<div>
{{ partial:components/btn type="submit" isButton="true" isFullwidth="true" wrapperClass="has-light-line" }}
{{ form_valuation:button_text }}
{{ /partial:components/btn }}
</div>
</div>
{{ /if }}
{{ /form:property_valuation }}
<script>
function formSetup() {
return {
formResult: false,
getResults(formElement) {
let context = this;
let data = new FormData(formElement);
let xhr = new XMLHttpRequest();
xhr.open(formElement.method, formElement.action);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(data);
xhr.onload = function() {
if (xhr.readyState === xhr.DONE) {
context.formResult = JSON.parse(xhr.response);
}
}
};
}
};
}
</script>
This {{ if success }} is not working here, is there a way to access this, like if i wasnt using AJAX? or is there an alternative way to update the content of the for to just display the success text?
I think the behavior you are experiencing is just as expected. The way Statamic works, it uses the conventional form POST process where the page is reloaded, and then success/errors are flashed to the session for your use.
But since you are using Ajax to handle the form submission, you have to use Javascript to handle both success and error states in your markup.
Here's an example of how you might handle your success and error messages:
This should help you to solve your problem, or take you few steps closer. You can modify the script to better suit your desired result. I hope it helps!