I’m having trouble getting Contact Form to work when posting through AJAX.
Form:
{% macro errorList(errors) %}
{% if errors %}
<ul class="errors">
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{% endmacro %}
{% from _self import errorList %}
<div id="my-form" class="form">
<form method="post" action="" accept-charset="UTF-8">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="contactForm/sendMessage">
<input type="hidden" name="redirect" value="contact/thanks">
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="medium-6 cell">
<h3><label for="fromEmail">Your Email</label></h3>
<input id="fromEmail" type="email" name="fromEmail" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}">
{{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}
</div>
<div class="medium-12 cell">
<h3><label for="message">Message</label></h3>
<textarea rows="10" cols="40" id="message" name="message">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
{{ message is defined and message ? errorList(message.getErrors('message')) }}
<input type="submit" value="Send">
</div>
<div id="thanks" style="opacity:0">THANKS</div>
</div>
</div>
</form>
</div>
jQuery:
$('#my-form').submit(function(ev) {
// Prevent the form from actually submitting
ev.preventDefault();
// Get the post data
var data = $(this).serialize();
// Send it to the server
$.post('/', data, function(response) {
if (response.success) {
$('#thanks').fadeIn();
} else {
// response.error will be an object containing any validation errors that occurred, indexed by field name
// e.g. response.error.fromName => ['From Name is required']
alert('An error occurred. Please try again.');
}
});
});
In this case the response is not a success so the alert is triggered.
Out of interest I console logged the response in the else block and it’s all the HTML on the page. And then I thought, why don’t I console log the data variable right after it’s declared and - same thing - it’s all the HTML on the page.
Anybody got any tips?