Menu Close

How to Prevent Multi-Submit on Contact Form 7

default

Recently, we came across an issue where we were using the Mail (2) setting to send an automated email to a user who submits the form with an attachment. The issue was that this attachment was a 2MB file, so before you see the success message, you have to wait for the attachment to be sent which can take a bit of time. Because of this, users end up submitting the forms various times causing multiple submits and emails send to both parties (Especially when using a 3rd party SMTP host like SendGrid or MailGun).

Here is the method we used to prevent this sort of action which can simply be added to your functions.php file to be called on each page.


<?php
	// Prevent Multi Submit on all WPCF7 forms
	add_action( 'wp_footer', 'prevent_cf7_multiple_emails' );

	function prevent_cf7_multiple_emails() {
	?>

	<script type="text/javascript">
	var disableSubmit = false;
	jQuery('input.wpcf7-submit[type="submit"]').click(function() {
	    jQuery(':input[type="submit"]').attr('value',"Sending...");
	    if (disableSubmit == true) {
	        return false;
	    }
	    disableSubmit = true;
	    return true;
	})
	  
	var wpcf7Elm = document.querySelector( '.wpcf7' );
	wpcf7Elm.addEventListener( 'wpcf7_before_send_mail', function( event ) {
	    jQuery(':input[type="submit"]').attr('value',"Sent");
	    disableSubmit = false;
	}, false );

	wpcf7Elm.addEventListener( 'wpcf7invalid', function( event ) {
	    jQuery(':input[type="submit"]').attr('value',"Submit")
	    disableSubmit = false;
	}, false );
	</script>
	<?php
} ?>

What the above will do is change the text of the forms submit button to ‘Sending…’ and disable any further clicks until the message is delivered. Once the message is delivered, the submit button will change to ‘Sent’.

In addition to this, if there are any errors in the form, we can use the wpcf7invalid DOM Event which we can use to change the value of the submit button back to the original value; in our case, we changed it back to ‘Submit’.

In our case, we had pages with multiple forms and only needed this to be added to one of the forms on the website. To do this, you can view the page source and get the ID attribute for the form (e.g. #wpcf7-f4-o1), and simply add this before each of the selectors, like so; jQuery('#wpcf7-f4-o1 :input[type="submit"]')

There are other ways of doing this such as using a preloader on submit but our particular client was pretty happy with the solution we provided him with.

Feel free to leave a comment below if this has helped or if you have another preferred method of performing such a task.

View Source
Posted in WordPress