[英]Doesn't send wp_mail() message with AJAX
我的页面上有一个表格。 我在没有插件的情况下使用 wp_mail() 发送数据。 提交代码在 function.php 中,我将表单作为简码粘贴到页面上。 表单有效,提交数据。 现在的问题是我想使用 AJAX 发送数据,这样页面就不会重新加载。 我写了代码,但它不起作用,页面仍然重新加载。 我怎样才能做到这一点?
//function.php function display_contact_form() { $mail = get_option('admin_email'); $subject = 'New message from '. $full_name; $message = $message. ' - The email address of the customer is: '. $mail; wp_mail($mail, $subject, $message); ?> <form id="contact-form" action="<?php echo esc_url(get_permalink()); ?>" method="post"> <input type="hidden" name="contact_form"> <div class="input-wrapp"> <input type="text" id="full-name" name="full_name" placeholder="Name"> </div> <div class="input-wrapp"> <input type="text" id="email" name="email" placeholder="Email"> </div> <div class="input-wrapp"> <textarea id="message" name="message" placeholder="Write something..."></textarea> </div> <button type="submit" id="contact-form-submit"> <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M1.81818 4.85279L9.39603 11.5887C9.74047 11.8948 10.2595 11.8948 10.604 11.5887L18.1818 4.85279V15.4547C18.1818 15.9567 17.7748 16.3637 17.2727 16.3637H2.72727C2.22519 16.3637 1.81818 15.9567 1.81818 15.4547V4.85279ZM3.1865 3.63647H16.8134L9.99995 9.69288L3.1865 3.63647Z" fill="white" /> </svg> Submit Message </button> </form> <?php }
//script.js $("#contact-form-submit").click(function() { $.ajax({ type: "POST", dataType: "html", url: "/wp-admin/admin-ajax.php", data: { action: "display_contact_form" }, success: function(response) { console.log("success") } }); });
事件处理程序将执行您的代码,然后 go 继续执行它通常执行的操作,除非您另有说明。 提交按钮将提交数据并加载新页面,除非您告诉它不要这样做。
您需要在事件处理程序中调用.preventDefault(),或返回false
以防止出现通常的行为。
然后在您的代码中:
//script.js
$("#contact-form-submit").click(function(event) { // pass the event object to the handler
event.preventDefault();
$.ajax({
type: "POST",
dataType: "html",
url: "/wp-admin/admin-ajax.php",
data: {
action: "display_contact_form"
},
success: function(response) {
console.log("success")
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.