-1

我正在尝试使多个 Ajax 表单在 Wordpress 循环中工作。我为每个表单中的表单和字段提供了一个唯一的 ID。我试图在 javascript 中引用每个表单以提交 AJAX 表单,但页面刷新就像它试图使用 php 提交表单一样。我不是专家,无法弄清楚这是如何工作的。该脚本适用于单个表单,因为我可以直接在 javascript 中引用实际的 form_id。我希望能够在循环中的每个帖子上提交表单,而无需刷新页面。在此先感谢您的帮助。

包含循环的模板中的 Javascript。

<script>
var form_id = $(this).closest("form").attr('id');
form_id.validate({
    highlight: function(element, errorClass, validClass) {
        $(element).parent('label').addClass('errors');
    },
    unhighlight: function(element, errorClass, validClass) {
        $(element).parent('label').removeClass('errors');
    },
    submitHandler: function(form) {
        $.ajax({
            type: "POST",
            url: '<?php echo admin_url(); ?>admin-ajax.php',
            data: form_id.serialize(),
            beforeSend: function() {
                $("input[name=submit],button", form).attr('disabled', 'disabled');
                $("div.loading", form).show();
                $("div.status", form).hide();
            },
            success: function(result) {
                if (result == 1 || result == '1') {
                    $("div.loading", form).hide();
                    $("div.thanks").slideDown();
                    document.forms["leadForm"].reset();
                } else {
                    $("div.loading", form).hide();
                    $("input[name=submit],button", form).removeAttr('disabled');
                    $("div.status", form).html(result).show();
                }
            }
        });
    }
});
</script>

循环内的表单。

<?php $pid = get_the_ID(); ?>
<form name="leadForm" method="post" id="leadForm-<?php echo $pid; ?>" action="#">
<div class="grid-x grid-padding-x">
    <div class="medium-12 cell">
        <textarea tabindex="2" rows="6" cols="30" maxlength="350" title="Please enter a message" name="message" id="message-<?php echo $pid; ?>" placeholder="Your message" ></textarea>
    </div>
    <div class="medium-6 cell">
        <label>Full Name
        <input type="text" placeholder="Full Name" class="required" autocomplete="off" name="fullname" id="fullname-<?php echo $pid; ?>"  >
        </label>
    </div>
    <div class="medium-6 cell">
        <label>Email Address
        <input type="email" placeholder="Email Address" class="required" autocomplete="off" name="email" id="email-<?php echo $pid; ?>" >
        </label>
    </div>
    <div class="medium-12 cell">
        <label>Phone Number
        <input type="tel" placeholder="Phone Number" class="required" autocomplete="off" name="phone" id="phone-<?php echo $pid; ?>" >
        </label>
    </div>
    <div class="medium-12 cell">
        <button class="button submit radius expanded" type="submit" >Send</button>
        <div class="loading" style="display:none;" >
            <img src="<?php echo get_template_directory_uri(); ?>/images/progress.gif" alt="Loading..." />
        </div>
        <div class="status callout radius alert small" style="display:none; text-align:center;">There was an error sending your message.
        </div>
        <div class="thanks callout radius success small" style="display:none; text-align:center;">Thank you.
        </div>
        <input type="hidden" name="current_url" value="<?php echo the_permalink(); ?>" class="button" />
        <input type="hidden" name="current_title" value="<?php echo the_title(); ?>"     class="button" />
    </div>
</div>
</form>

Wordpress 中的 php 脚本 - functions.php

<?php
add_action('wp_ajax_nopriv_leadForm', 'core_leadForm');
add_action('wp_ajax_leadForm', 'core_leadForm');
    function core_leadForm()
        {
            if (!((isset($_POST['fullname']) && !empty($_POST['fullname'])) && (isset($_POST['email']) && !empty($_POST['email'])) && (isset($_POST['phone']) && !empty($_POST['phone'])) && (isset($_POST['message']) && !empty($_POST['message'])) ))
                {
                    echo 'Enter all fields';
                }
            else if (!is_email($_POST['email']))
                {
                    echo 'Email is not valid';
                }
            else
                {
                    if (function_exists('ot_get_option'))
                        {
                            //$to = ot_get_option('cont_email');
                            $to = 'email@website.com';
                        }
                    else
                        {
                            $to = '';
                        }
                }
        }
    ob_start();
?>
<br>
<table>
    <tr>
        <td><b><u>CONTACT DETAILS</u></b><br>
            <br></td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td><b>Full Name:</b></td>
        <td><?php echo $_POST['fullname'] ?></td>
    </tr>
    <tr>
        <td><b>Phone Number:</b></td>
        <td><?php echo $_POST['phone'] ?></td>
    </tr>
    <tr>
        <td><b>Email Address:</b></td>
        <td><?php echo $_POST['email'] ?></td>
    </tr>
    <tr>
        <td><b>Link:</b></td>
        <td><a href="<?php echo $_POST['current_url'] ?>"><?php echo $_POST['current_title'] ?></a></td>
    </tr>
    <tr>
        <td><b>Message:</b></td>
        <td><?php echo $_POST['message'] ?></td>
    </tr>
</table>

<?php
    $message = ob_get_contents();
    ob_end_clean();
    $subject = 'NEW MESSAGE';
    $headers[] = 'From: ' . $_POST["fullname"] . ' <' . $_POST["email"] . '>';
    add_filter('wp_mail_content_type', 'core_html_content_type');
    function core_html_content_type()
        {
            return 'text/html';
        }
    if (wp_mail($to, $subject, $message, $headers))
        {
            // echo "test";
            echo 1;
        }
    else
        {
            echo 'Your message failed to send. Please try again.';
        }
        die();
?>
4

1 回答 1

0

很难复制 WP 可能与您的代码有关的所有问题。但这将是其中之一:

  1. this当在对 html 对象的引用之外使用时,指的是window. .closest向上移动 dom 树,而不是向下移动,因此它不会在 window 对象中找到表单。你想要达到的效果可以通过 来实现$('form').attr('id'),即返回找到的第一种形式的 id。
  2. 您需要确保$在使用前已定义,这是使用 jquery 随附版本的 WP 怪癖,您将单词替换jQuery$
  3. 我没有看到任何证据表明 jQuery 在您使用它时已加载,您还使用了另一个库,.validate使用$(document).ready();

顺便说一句,学习如何使用控制台(例如在 chrome 中),您可以在此处输出 js 以测试变量,代码中的任何错误也会在这里输出。

于 2018-02-28T20:02:53.020 回答