【问题标题】:Wordpress AJAX submit results opens in admin-ajax.php instead of content divWordpress AJAX 提交结果在 admin-ajax.php 而不是内容 div 中打开
【发布时间】:2020-03-09 15:58:42
【问题描述】:

所以,我对 wordpress 的 AJAX 处理程序有疑问。 这是我的表格:

form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter" name="filter">
            <input type="hidden" name="action" value="myfilter">
            <?php
                if( $terms = get_terms( array( 'taxonomy' => 'category', 'orderby' => 'name' ) ) ) :

                    echo '<div class="d-flex justify-content-center">';

                    foreach ( $terms as $term ) :
                        if($first) : echo '<label><input type="radio" class="radio-formular" value="' . $term->term_id . '" name="categoryfilter" onclick="this.form.submit();" checked>' . $term->name.'</label>'; // ID of the category 
                        else : echo '<label><input type="radio" class="radio-formular" value="' . $term->term_id . '" name="categoryfilter">' . $term->name. '</label>'; // ID of the category as the value
                        endif;

                    endforeach;
                echo '</div>';
            endif;
        ?>

        <button id="sbm">Apply</button>


    </form>

我希望,当我选择其中一个收音机时,表单将提交并由下一段代码处理:

<script type="text/javascript">
    jQuery(function($){
    $('#filter').submit(function(e){
        var filter = $('#filter');
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(), // form data
            type:filter.attr('method'), // POST
            beforeSend:function(xhr){
                //filter.find('button').text('Processing...'); // changing the button label
            },
            success:function(data){
                //filter.find('button').text('Apply filter'); // changing the button label back
                $('#response').html(data); // insert data
            }
        });
        return false;
    });
});


</script>

两个 sn-ps 都在同一个文件中。

functions.php

add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE} 
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');

function misha_filter_function(){
    $args = array(
        'orderby' => 'date', // we will sort posts by date
        'order' => $_POST['date'] // ASC or DESC
    );

    // for taxonomies / categories
    if( isset( $_POST['categoryfilter'] ) && $_POST['categoryfilter'] != '0' )
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $_POST['categoryfilter']
            )
        );


    // if you want to use multiple checkboxed, just duplicate the above 5 lines for each checkbox

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
        while( $query->have_posts() ): $query->the_post();
            echo '<div class="container-apartament m-3 text-center">';
                echo '<img src="'. wp_get_attachment_url(get_post_thumbnail_id($query->post->ID),'full') .'">';
                echo '<div class="mt-2 mb-2 card-body">';
                    echo '<h4>' . $query->post->post_title . '</h4>';
                    echo '<a href="#myModal-'. $query->post->ID . '" class="band-text-inner"><img src="wp-content/uploads/2020/03/house-plan.png"> Plan </a>';
                    echo '<p class="card-price">'. get_field("price") .'€ no VAT</p>';
                    echo '<p class="card-yield">'. get_field("yield") .' NET <span class="text-mic-card">yield/yr: '. (string)0.05*get_field("price")*1000 .' € </span></p>';
                    echo '<a href="'. get_permalink() .'" class="invest-now">Invest Now </a>';
                echo '</div>';
            echo '</div>';
        endwhile;
        wp_reset_postdata();
    else :
        echo 'No posts found';
    endif;

    die();
}

问题是: 通过按钮提交表单按预期工作,但是当我在单选按钮上设置 onclick 事件时,它卡在 admin-ajax.php 中而不是返回值。错误在哪里?自午餐以来我一直在努力解决这个问题,我似乎找不到解决方案。 我尝试过 preventDefault(),正如我在另一篇文章中看到的那样,但它阻止了表单提交,我根本没有得到任何回应。 对不起,我的英语不好和/或模棱两可的解释,提前感谢!

【问题讨论】:

  • "它卡在 admin-ajax.php 中而不是返回值" 调试模式是否开启?如果是,显示的错误是什么?
  • 自定义字段键正确啊?
  • 我认为自定义字段值错误?
  • 当它到达 admin-ajax.php 时,它会在此处显示信息。我想这些字段没问题,因为当我通过按钮提交表单时一切正常。当我在另一个输入元素(如 radio 或 input type="submit" 上调用提交函数时出现问题

标签: javascript php jquery ajax wordpress


【解决方案1】:

我为这些人找到了解决方法。我设法添加了一个 onclick 事件,该事件触发对使一切正常的按钮的单击。不过,无法通过字段提交表单是有原因的,如果我找到了,我会在这里发布。

【讨论】:

    【解决方案2】:

    这是一个 sn-p,它是我认为您正在尝试的框架:

    • 阻止表单实际提交(这样就不会加载新页面)
    • 在提交表单时执行默认设置以外的操作(例如,它只是简单地登录到控制台,但它也可以很容易地成为 Ajax 请求)
    • 当表单值改变时触发非默认动作

    jQuery(function($) {
      $('#mainForm').on('submit', function(event) {
        event.preventDefault()
        // Do whatever you want to happen when the form "submits" here, such as your ajax request
        // in the current context "this" refers to the form html object, not the jquery object
        console.info('Running submit action. Form data:', $(this).serialize())
      }).on('change', function(event){
        // trigger a submit anytime something in the form sends a 'change' action. 
        //You could also filter this to specific items in the form if you wanted
        console.warn('form changed')
        // use jquery to trigger the submit event
        // in the current context "this" refers to the form html object, not the jquery object
        // note that if you do `this.submit()` the form will submit and the submit handler won't be called
        $(this).trigger('submit')
      })
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <form action="https://postman-echo.com/get" id="mainForm">
      <label><input type="radio" name="radioChoice" value="a"/>a</label>
      <label><input type="radio" name="radioChoice" value="b"/>b</label>
    </form>

    请注意,当单选按钮的值发生更改时,表单会触发提交事件,但不会加载新页面。要查看不同之处,请尝试编辑 sn-p 以便不使用查询触发提交,而是在表单 DOM 对象上调用 .submit()(在更改处理程序中调用 this.submit())。在 DOM 对象上调用 submit 会绕过 jQuery 事件处理程序。

    如果您的表单只有单选按钮,则在每次更改时触发提交事件都可以正常工作,但如果您有可以快速更改的字段(如文本输入),您可能不想触发这么多事件,所以您可以使用something 去抖动或限制提交操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      相关资源
      最近更新 更多