使用带有快捷码的AJAX提交表单时出错

时间:2018-02-24 作者:Eh Jewel

我为用户提交表单创建了一个快捷代码。我想在不加载页面的情况下提交此表单(Ajax)。

这是我的短代码

add_shortcode(\'et-test-plugin_shortcode\', function($atts, $content) {

    $atts = shortcode_atts(array(
        \'name-field\' => \'Name\',
        \'phone-field\' => \'Phone Number\',
        \'email-field\' => \'Email Address\',
        \'budget-field\' => \'Desired Budget\',
        \'min-budget\' => \'1000\',
        \'max-budget\' => \'10000\',
        \'message-field\' => \'Message\',
        \'submit-btn-label\' => \'Submit\',
    ), $atts);

    ob_start();
    ?>
    <form action="<?php echo admin_url(\'admin-ajax.php\'); ?>" class="et_test_form" method="post">
        <div class="row">
            <div class="col-sm-6">
                <input type="text" name="_name" placeholder="<?php echo esc_attr($atts[\'name-field\']) ?>">
            </div>
            <div class="col-sm-6">
                <input type="text" name="_phone" placeholder="<?php echo esc_attr($atts[\'phone-field\']) ?>">
            </div>
            <div class="col-sm-6">
                <input type="email" name="_email" placeholder="<?php echo esc_attr($atts[\'email-field\']) ?>">
            </div>
            <div class="col-sm-6">
                <input type="number" name="_budget" min="<?php echo esc_attr($atts[\'min-budget\']) ?>" max="<?php echo esc_attr($atts[\'max-budget\']) ?>" placeholder="<?php echo esc_attr($atts[\'budget-field\']) ?>">
            </div>
        </div>
        <textarea class="form-control" rows="3" cols="10" name="_message" placeholder="<?php echo esc_attr($atts[\'message-field\']) ?>"></textarea>
        <input type="submit" name="submit" value="<?php echo $atts[\'submit-btn-label\']; ?>"/>
        <div id="note"></div>
    </form>
    <?php

    $html = ob_get_clean();

    add_action(\'wp_ajax_et_test_plugin_create_post\', \'et_test_plugin_create_post\');
    add_action(\'wp_ajax_nopriv_et_test_plugin_create_post\', \'et_test_plugin_create_post\');

    function et_test_plugin_create_post() {
        if (isset($_POST[\'submit\'])) {
            $name = !empty($_POST[\'_name\']) ? $_POST[\'_name\'] : \'\';
            $phone = !empty($_POST[\'_phone\']) ? $_POST[\'_phone\'] : \'\';
            $email = !empty($_POST[\'_email\']) ? $_POST[\'_email\'] : \'\';
            $budget = !empty($_POST[\'_budget\']) ? $_POST[\'_budget\'] : \'\';
            $message = !empty($_POST[\'_message\']) ? $_POST[\'_message\'] : \'\';
            if ($name) {
                wp_insert_post(
                    array(
                        \'post_title\' => wp_strip_all_tags($name) . \' submitted a form\',
                        \'post_type\' => \'customer\',
                        \'post_status\' => \'private\', /* Or "draft", if required */
                        \'meta_input\' => array(
                            \'et-test-plugin_customer_name\' => wp_strip_all_tags($name),
                            \'et-test-plugin_customer_phone\' => wp_strip_all_tags($phone),
                            \'et-test-plugin_customer_email\' => wp_strip_all_tags($email),
                            \'et-test-plugin_customer_budget\' => wp_strip_all_tags($budget),
                            \'et-test-plugin_customer_message\' => wp_strip_all_tags($message),
                        )
                    )
                );
            }
        }
    }

    ?>
    <script type="text/javascript">
        var $a = jQuery.noConflict();

        $a(window).load(function(){

            $a(".et_test_form").submit(function(e){

                e.preventDefault();
                var input_data = $a(this).serialize();
                $a.ajax({
                    type: "POST",
                    url: "<?php echo admin_url(\'admin-ajax.php\') ?>",
                    data: input_data,
                    action: \'et_test_plugin_create_post\',
                    success: function(alrt){
                        $a("#note").ajaxComplete(function(event, request, settings){
                            if(alrt == "OK"){
                                result = "Thanks for sending the message.";
                                $a(".et_test_form").hide();
                            } else {
                                result = \'Error\';
                            }
                            $a(this).html(result);
                        });
                    }
                });

                return false;
            });
        });

    </script>
    <?php

    return $html;

});
我真的不知道为什么会出现这种返回错误。很可能wp_ajax_et_test_plugin_create_post 操作在短代码中无效。

2 个回复
最合适的回答,由SO网友:obiPlabon 整理而成

我喜欢解决问题并保持这种习惯,我已经解决了你的问题。有很多问题。现在表单和ajax工作得很好,但仍然存在一些问题。例如,您没有使用nonce或CSRF令牌,这将导致CSRF。您没有使用任何验证,这也是一个重要问题。您没有检查用户功能和登录状态,不确定这是功能还是错误。

顺便说一句,这是工作代码-

function et_text_render_plugin_shortcode( $atts, $content ) {
    $atts = shortcode_atts( array(
        \'name-field\'       => \'Name\',
        \'phone-field\'      => \'Phone Number\',
        \'email-field\'      => \'Email Address\',
        \'budget-field\'     => \'Desired Budget\',
        \'min-budget\'       => \'1000\',
        \'max-budget\'       => \'10000\',
        \'message-field\'    => \'Message\',
        \'submit-btn-label\' => \'Submit\',
    ), $atts );

    ob_start();
    ?>

    <form class="et_test_form" method="post">
        <div class="row">
            <div class="col-sm-6">
                <input type="text" name="_name" placeholder="<?php echo esc_attr( $atts[\'name-field\'] ); ?>">
            </div>
            <div class="col-sm-6">
                <input type="text" name="_phone" placeholder="<?php echo esc_attr( $atts[\'phone-field\'] ); ?>">
            </div>
            <div class="col-sm-6">
                <input type="email" name="_email" placeholder="<?php echo esc_attr( $atts[\'email-field\'] ); ?>">
            </div>
            <div class="col-sm-6">
                <input type="number" name="_budget" min="<?php echo esc_attr( $atts[\'min-budget\'] ); ?>" max="<?php echo esc_attr( $atts[\'max-budget\'] ); ?>" placeholder="<?php echo esc_attr( $atts[\'budget-field\'] ); ?>">
            </div>
        </div>
        <textarea class="form-control" rows="3" cols="10" name="_message" placeholder="<?php echo esc_attr( $atts[\'message-field\'] ); ?>"></textarea>
        <input type="submit" name="submit" value="<?php echo esc_attr( $atts[\'submit-btn-label\'] ); ?>"/>
    </form>
    <div id="note"></div>
    <script>
        jQuery( function( $ ) {
            $( ".et_test_form" ).on( "submit", function( e ) {
                e.preventDefault();
                var result = \'\',
                    ajax_url = "<?php echo esc_url_raw( admin_url( \'admin-ajax.php\' ) ); ?>";

                $.post(
                    ajax_url,
                    {
                        data: $( this ).serialize(),
                        action: \'et_test_plugin_create_post\'
                    },
                    function( res ){
                        if ( res.success ) {
                            $( ".et_test_form" ).hide();
                        }
                        $( "#note" ).html( res.data.message );
                    }
                );

                return false;
            } );
        } )
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode( \'et-test-plugin_shortcode\', \'et_text_render_plugin_shortcode\' );

function et_test_plugin_create_post() {
    if ( isset( $_POST[\'data\'] ) ) {
        $data = array();
        wp_parse_str( $_POST[\'data\'], $data );

        $name    = ! empty( $data[\'_name\'] ) ? $data[\'_name\']    : \'\';
        $phone   = ! empty( $data[\'_phone\'] ) ? $data[\'_phone\']  : \'\';
        $email   = ! empty( $data[\'_email\'] ) ? $data[\'_email\']  : \'\';
        $budget  = ! empty( $data[\'_budget\'] ) ? $data[\'_budget\']: \'\';
        $message = ! empty( $data[\'_message\'] ) ? $data[\'_message\'] : \'\';

        $post = array(
            \'post_title\'  => wp_strip_all_tags( $name ) . \' submitted a form\',
            \'post_type\'   => \'customer\',
            \'post_status\' => \'private\', /* Or "draft", if required */
            \'meta_input\'  => array(
                \'et-test-plugin_customer_name\'    => wp_strip_all_tags( $name ),
                \'et-test-plugin_customer_phone\'   => wp_strip_all_tags( $phone ),
                \'et-test-plugin_customer_email\'   => wp_strip_all_tags( $email ),
                \'et-test-plugin_customer_budget\'  => wp_strip_all_tags( $budget ),
                \'et-test-plugin_customer_message\' => wp_strip_all_tags( $message ),
            )
        );

        if ( $name ) {
            wp_insert_post( $post );

            wp_send_json_success( array(
                \'message\' => \'Added successfully!\',
            ) );
        }
    }
    wp_send_json_error( array(
        \'message\' => \'Something went wrong!\',
    ) );
}
add_action( \'wp_ajax_et_test_plugin_create_post\', \'et_test_plugin_create_post\' );
add_action( \'wp_ajax_nopriv_et_test_plugin_create_post\', \'et_test_plugin_create_post\' );

SO网友:mmm

2“add\\u action ajax…”仅在执行短代码时执行。然后,ob_get_clean 不是个好地方

为了工作,这些操作需要与以下短代码分开:

add_shortcode(\'et-test-plugin_shortcode\', function($atts, $content) {

    //$atts = shortcode_atts ...

    ob_start();
    ?>
        <form action="<?php echo admin_url(\'admin-ajax.php\'); ?>" class="et_test_form" method="post">
            <!-- ... -->
        </form>

        <script type="text/javascript">
            //...
        </script>
    <?php
    $html = ob_get_clean();

    return $html;

});


add_action(\'wp_ajax_et_test_plugin_create_post\', \'et_test_plugin_create_post\');
add_action(\'wp_ajax_nopriv_et_test_plugin_create_post\', \'et_test_plugin_create_post\');

function et_test_plugin_create_post() {
    // ....
}

结束

相关推荐

当函数在子主题上但不在插件页面中时,AJAX工作

我有一个ajax,它将一些jQuery变量传递给PHP函数。我的函数应该在类文件中。但ajax无法工作并显示bad request. 但如果我把php函数放在我的子主题中,它就会工作得很好。这是我的jQuery AJAX $.ajax({ type: \'POST\', url: ajaxurl, data: { action: \'thwec_get_element_block