简体   繁体   中英

Multiple Ajax Forms using Wordpress Loop

I am trying to make multiple Ajax forms work in a Wordpress loop. I have given the form and fields in each form a unique 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. 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. 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.

<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

<?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. But it would be one of these:

  1. this when used outside of an reference to an html object refers to window . .closest travels up the dom tree, not down, so it will not find forms within the window object. 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.
  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 $
  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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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