使用Wordpress时无法刷新提交页面的联系表单

时间:2018-09-19 02:31:13

标签: javascript php html ajax wordpress

我已经设置了以下代码,以使联系人表单提交后不会刷新页面。

HTML:

<form method="POST" id="contact-form">
  <div class="contact-element flex-row">
    <input class="" type="text" name="name" placeholder="Name" id="name" Required>
    <input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
  </div>
  <input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
  <textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
  <input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
    <input type="hidden" name="action" value="form-action">
</form>

JavaScript / AJAX请求:

$("#contact-form").submit(function(event) {
  event.preventDefault();
  var $form = $( this ),
      url = "<?php echo get_template_directory_uri(); ?>/library/contact-form.php";
  var posting = $.post( url, {
    name: $('#name').val(),
    email: $('#email').val(),
    subject: $('#subject').val(),
    message: $('#message').val(),
  });
  posting.done(function( data ) {
    alert('success');
  });
});

PHP:

// Set $to as the email you want to send the test to.
$to = "my@email.com";

// Email subject and body text.
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$headers .= "Reply-To: ". strip_tags($_POST['email']) . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = $_POST["message"];

// send test message using wp_mail function.
if(isset(($_POST['name']), ($_POST['email']), ($_POST['message']), ($_POST["subject"]))) {
  $sent_message = wp_mail( $to, $subject, $message, $headers );
} else {

};

//display message based on the result.
if ( $sent_message ) {
    // The message was sent.
    echo 'The test message was sent. Check your email inbox.';
} else {
    // The message was not sent.
    echo 'The message was not sent!';
}

当我在本地网站上运行该代码时,该代码有效,它返回成功警报。 PHP代码还成功将联系表单信息发送到我的电子邮件地址。

在Web服务器上运行它时,我得到一个“服务器响应状态为500(内部错误)”。

我想我一定在这里忽略了一些愚蠢的事情,但我看不到,希望其他人可以看到并帮助我? 预先感谢!

1 个答案:

答案 0 :(得分:0)

这就是我为表单提交Ajax的方式。它包含WordPress安全措施,您可以从Google详细了解它们,但是我会提供一些小描述。

HTML

<form method="POST" id="contact-form">
    <div class="contact-element flex-row">
        <input class="" type="text" name="name" placeholder="Name" id="name" Required>
        <input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
    </div>
    <input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
    <textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
    <input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
    <input type="hidden" name="action" value="contact_form" id="cf_action" url="<?= admin_url('admin-ajax.php'); ?>">
    <?php wp_nonce_field( 'contact_form', 'contact_form_wpnonce' ); ?>
</form>

Javascript

jQuery(function($){
    $("#contact-form").submit(function(e){
        var url = $('#cf_action').attr('url');
        $.ajax({
            type: "POST",
            url: url,
            data: $("#contact-form").serialize(),
            success: function(data) { 
                alert(data.data);
            }
        });
        e.preventDefault(); // avoid to execute the actual submit of the form.
    });
});

功能

add_action('wp_ajax_contact_form', 'contact_form_function');
add_action('wp_ajax_nopriv_contact_form', 'contact_form_function'); 
function contact_form_function()
{   
    if ( !isset($_POST['xyz_contact_email_meta_box_nonce']) && !wp_verify_nonce($_POST['xyz_contact_email_meta_box_nonce'], 'xyz_save_contact_email_data')) {
        # code...
        return;
    }
    $user_name  = sanitize_text_field( $_POST['name'] );
    $user_email = sanitize_email( $_POST['email'] );
    $user_subject = sanitize_text_field( $_POST['subject'] );
    $user_message = sanitize_textarea_field( $_POST['message'] );
    $to = 'xyz@gmail.com';
    $subject = $user_subject;
    $body = 'Hi you recived a message from '.$user_name.'('.$user_email.'),<p>'.$user_message.'</p>';
    $headers = array('Content-Type: text/html; charset=UTF-8');
    $status = wp_mail( $to, $subject, $body, $headers );
    if($status){
        wp_send_json_success('sent successful');
    }else{
        wp_send_json_error('something went wrong');
    }
}

说明

好的,让我指导一下WordPress。 WordPress已经内置了功能,可以处理来自其主题的functions.php的ajax请求。您必须复制并粘贴要显示表单的html代码,页脚中的js代码和functions.php中的功能代码

以下是一些提示:-

  1. wp_nonce_field =用于安全目的,可防止黑客将表格用于其他目的。
  2. 清理数据以确保您不会从发布的数据中接收到任何恶意代码,也可以使用esc_attr(它将任何标签和脚本转换为html)。
  3. 使用WordPress默认功能wp_send_json_success和wp_send_json_error发送数据是一种好习惯。

(如果您难以理解,请原谅我,因为这是我关于stackoverflow的第一个答案) 干杯!