Skip to content

Instantly share code, notes, and snippets.

@algb12
Last active January 4, 2021 20:12
Show Gist options
  • Save algb12/60b28bebc045c1576addc84065c494c2 to your computer and use it in GitHub Desktop.
Save algb12/60b28bebc045c1576addc84065c494c2 to your computer and use it in GitHub Desktop.
Code to AJAXify The Newsletter Plugin subscription form
<script type="text/javascript" id="tnp-subscription-ajax">
// Wait for jQuery to load
jQuery(document).ready(function($) {
// Identify form through submit button
var form = $('.tnp-submit').parent().closest('form');
// This is the syntax to target the form associated with the submit button (keeps form validation)
form.submit(function(e) {
// Only trigger if it's the subscribe form, and not any other type of form
if (form.attr('action').endsWith("?na=s")) {
// Prevent submit button from actually submitting (and taking user away from origin page)
e.preventDefault();
// AJAX request itself
$.ajax({
method: 'POST',
type: 'POST',
url: '/wp-json/newsletter/v1/subscribe',
data: {
// Name selector syntax to target inputs
email: $('input[name="ne"]').val(),
name: $('input[name="nn"]').val(),
surname: $('input[name="ns"]').val(),
send_emails: true
},
// Prevent paranoid clicking behaviour from user
beforeSend: function() {
$(".tnp-submit").first().prop('disabled', true);
$('.tnp-submit').first().val('Subscribing...');
},
// When AJAX request is complete
complete: function(e, xhr) {
if (e.status === 200) {
// If everything is OK
// Success notification
alert('Success: Your subscription to our newsletter was successful - please check your inbox for a confirmation email!');
// Disable form controls to prevent re-submitting
$(".tnp-submit").first().val("Subscribed!");
$(".tnp-submit").first().prop('disabled', true);
$('input[name="ne"]').prop('disabled', true);
$('input[name="ns"]').prop('disabled', true);
$('input[name="nn"]').prop('disabled', true);
$('input[name="ny"]').prop('disabled', true);
} else {
// If error, re-enable form controls to allow user to try again
$('.tnp-submit').first().val('Subscribe');
$(".tnp-submit").first().prop('disabled', false);
// Error notification
alert('Error: ' + e['responseText']);
}
}
});
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment