简体   繁体   English

使用 Wordpress Loop 的多个 Ajax 表单

[英]Multiple Ajax Forms using Wordpress Loop

I am trying to make multiple Ajax forms work in a Wordpress loop.我正在尝试使多个 Ajax 表单在 Wordpress 循环中工作。 I have given the form and fields in each form a unique ID.我为每个表单中的表单和字段提供了一个唯一的 ID。 I'm trying to reference each form within the javascript in order to submit the AJAX form but instead the page refreshes as if it's trying to submit the form using php.我试图在 javascript 中引用每个表单以提交 AJAX 表单,但页面刷新,好像它正在尝试使用 php 提交表单。 I am no expert and can't figure out how this works.我不是专家,无法弄清楚这是如何工作的。 The script works for an individual form as I can reference the actual form_id directly within the javascript.该脚本适用于单个表单,因为我可以直接在 javascript 中引用实际的 form_id。 I want to be able to submit the form on each post within the loop without having to refresh the page.我希望能够在循环内的每个帖子上提交表单,而无需刷新页面。 Thanks in advance for your help.在此先感谢您的帮助。

Javascript in the template that contains the loop.包含循环的模板中的 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>

The form within the loop.循环内的形式。

<?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>

The php script within the Wordpress - functions.php 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();
?>

Hard to replicate all the issues that WP might have with your code.很难复制 WP 可能在您的代码中遇到的所有问题。 But it would be one of these:但这将是其中之一:

  1. this when used outside of an reference to an html object refers to window . this当在对 html 对象的引用之外使用时是指window .closest travels up the dom tree, not down, so it will not find forms within the window object. .closest沿着 dom 树.closest移动,而不是向下移动,因此它不会在 window 对象中找到表单。 The same effect of what you want to achieve can be achieved by $('form').attr('id') , ie return the id of the 1st form found.可以通过$('form').attr('id')实现您想要实现的相同效果,即返回找到的第一个表单的 id。
  2. You need to ensure $ is defined before using, this is a WP quirk of using the shipped version of jquery, you substitute the word jQuery for $您需要确保在使用之前定义了$ ,这是使用 jquery 的附带版本的 WP 怪癖,您将单词jQuery替换为$
  3. I see no evidence that jQuery is loaded by the time you use it, you are also using another library, .validate , make use of $(document).ready();我没有看到任何证据表明 jQuery 在您使用它时已加载,您还使用了另一个库.validate ,利用$(document).ready();

Also on a side note, learn how to use the console (eg in chrome), you can output js here to test variables, any errors in your code will output here too.另外附带说明,学习如何使用控制台(例如在 chrome 中),您可以在此处输出 js 以测试变量,您的代码中的任何错误也会在此处输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM