I have multiple AJAX forms on a single page but they won't submit. The forms are within a Wordpress loop and each form has a unique ID. I've defined the form ID variable so I can trigger the current form ID to submit.
JAVASCRIPT
<script type="text/javascript">
jQuery(document).ready(function ($) {
var formID = $('form').attr('id')
var is_sending = false,
failure_message = 'Whoops, looks like there was a problem. Please try again later.';
formID.submit(function (e) {
if (is_sending || !validateInputs()) {
return false; // Don't let someone submit the form while it is in-progress...
}
e.preventDefault(); // Prevent the default form submit
$this = $(this); // Cache this
$.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>', // Let WordPress figure this url out...
type: 'post',
dataType: 'JSON', // Set this so we don't need to decode the response...
data: $this.serialize(), // One-liner form data prep...
beforeSend: function () {
is_sending = true;
// You could do an animation here...
},
error: handleFormError,
success: function (data) {
if (data.status === 'success') {
// Here, you could trigger a success message
} else {
handleFormError(); // If we don't get the expected response, it's an error...
}
}
});
});
function handleFormError () {
is_sending = false; // Reset the is_sending var so they can try again...
alert(failure_message);
}
function validateInputs () {
var $name = $('#contact-form > input[name="name"]').val(),
$email = $('#contact-form > input[name="email"]').val(),
$message = $('#contact-form > textarea').val();
if (!$name || !$email || !$message) {
alert('Before sending, please make sure to provide your name, email, and message.');
return false;
}
return true;
}
});
</script>
FORM
<form id="contact-form-<?php echo $pid; ?>">
<input type="hidden" name="action" value="contact_send" />
<input type="text" name="name" placeholder="Your name..." />
<input type="email" name="email" placeholder="Your email..." />
<textarea name="message" placeholder="Your message..."></textarea>
<input class="button expanded" type="submit" value="Send Message" />
</form>