Just playing around with Wordpress / Contact Form 7
.
Is it possible to add custom javascript function on successful email send event?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Write this in additional settings at the bottom of the contact form configuration page:
on_sent_ok: "some js code here"
UPDATE: You can use it to call functions like this:
on_sent_ok: "your_function();"
Or write some code (this one redirects to thank you page):
on_sent_ok: "document.location='/thank-you-page/';"
回答2:
Contact Form 7 emits a number of Javascript events that bubble up to the document object. In version 4.1 they can be found in contact-form-7/includes/js/scripts.js. If you're using jQuery you can access those events like this:
$(document).on('spam.wpcf7', function () {
console.log('submit.wpcf7 was triggered!');
});
$(document).on('invalid.wpcf7', function () {
console.log('invalid.wpcf7 was triggered!');
});
$(document).on('mailsent.wpcf7', function () {
console.log('mailsent.wpcf7 was triggered!');
});
$(document).on('mailfailed.wpcf7', function () {
console.log('mailfailed.wpcf7 was triggered!');
});
回答3:
try this:
$( document ).ajaxComplete(function( event,request, settings ) {
if($('.sent').length > 0){
console.log('sent');
}else{
console.log('didnt sent');
}
});
回答4:
Example 1:
on_sent_ok: "location = 'http://mysite.com/thanks/';"
Example 2: In form script:
<div id="hidecform">
<p>You name<br />
[text* your-name] </p>
...
</div>
Then at the bottom of the admin page under "Additional Settings" put the following:
on_sent_ok: "document.getElementById('hidecform').style.display = 'none';"
回答5:
Just a quick note that on_sent_ok is deprecated.
Contact form 7 is now using event listeners, like this;
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '11875' == event.detail.contactFormId ) { // if you want to identify the form
// do something
}
}, true );
</script>
Then add this to the wp_footer action.
like this;
add_action( 'wp_footer', 'wp1568dd4_wpcf7_on_sent' );
function wp1568dd4_wpcf7_on_sent() {
// the script above
}