• Hi,

    I have a list of categories that I am trying to filter my custom post type by, I know there are plugins that do this but would rather not use them.

    I am using the following code but am receiving a “POST https://www.goldpine.co.nz/wp-admin/admin-ajax.php 400 (Bad Request):”

    Any ideas how to fix this or something in the code I am missing?

    <form action=”<?php echo site_url() ?>/wp-admin/admin-ajax.php” method=”POST” id=”filter”>
    <?php if( $terms = get_terms( ‘category’, ‘orderby=name’ ) ) :
    echo ‘<select name=”categoryfilter”><option>Select category…</option>’;
    foreach ( $terms as $term ) :
    echo ‘<option value=”‘ . $term->term_id . ‘”>’ . $term->name . ‘</option>’; // ID of the category as the value of an option
    endforeach;
    echo ‘</select>’;
    endif;
    ?>

    <button>Apply filter</button>
    <input type=”hidden” name=”action” value=”myfilter”>
    </form>
    <div id=”response”></div>

    <script type=”text/javascript”>

    jQuery(function($){
    $(‘#filter’).submit(function(){
    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>

Viewing 8 replies - 1 through 8 (of 8 total)
  • Do you have a PHP function that is for responding to this request?
    It looks like you are calling ‘myfilter’, without a nonce(which could be dangerous).
    The ajax function must have an action parameter which is used for the add_action call, and it needs a nonce.
    So, your PHP function should be added to the action named ‘wp_ajax_myfilter’ or ‘wp_ajax_nopriv_myfilter’, depending on whether you want it available for logged in users or logged out users.

    add_action('wp_ajax_myfilter', 'myPHP_function_to_handle_categories');
    add_action('wp_ajax_nopriv_myfilter', 'myPHP_function_to_handle_categories');
    • This reply was modified 6 years, 9 months ago by Joy.
    Thread Starter courtneyjouning

    (@courtneyjouning)

    Read and read but no luck, can you please assist with my code:

    <form action=”<?php echo site_url() ?>/wp-admin/admin-ajax.php” method=”POST” id=”filter”>
    <?php
    if( $terms = get_terms( ‘category’, ‘orderby=name’ ) ) : // to make it simple I
    use default categories
    echo ‘<select name=”categoryfilter”><option>Select category…</option>’;
    foreach ( $terms as $term ) :
    echo ‘<option value=”‘ . $term->term_id . ‘”>’ . $term->name . ‘</option>’; //
    ID of the category as the value of an option
    endforeach;
    echo ‘</select>’;
    endif;
    ?>
    <button>Apply filter</button>
    <input type=”hidden” name=”action” value=”myfilter”>
    </form>
    <div id=”response”></div>
    <script type=”text/javascript”>
    jQuery(function($){
    $(‘#filter’).submit(function(){
    var filter = $(‘#filter’);
    $.ajax({
    url:filter.attr(‘action’),
    data:filter.serialize(), // form data
    ‘action’:’myfilter’,
    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>
    <?php

    function video_filter_function(){
    $args = array(
    ‘orderby’ => ‘date’, // we will sort posts by date
    ‘order’ => $_POST[‘date’] // ASC или DESC
    );

    // for taxonomies / categories
    if( isset( $_POST[‘categoryfilter’] ) )
    array(
    ‘taxonomy’ => ‘category’,
    ‘field’ => ‘id’,
    ‘terms’ => $_POST[‘categoryfilter’]
    )
    );

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
    while( $query->have_posts() ): $query->the_post();
    echo ‘<h2>’ . $query->post->post_title . ‘</h2>’;
    endwhile;
    wp_reset_postdata();
    else :
    echo ‘No posts found’;
    endif;

    die();
    }

    add_action(‘wp_ajax_myfilter’, ‘video_filter_function’);
    ?>

    OK, first thing is to put your PHP function that handles the ajax call into your functions.php file, so that it is always already loaded when called. That includes the add_action call. The way you have it, the add_action is last and would not be executed until the archive page is loaded, which is late and not done by the admin-ajax handler.

    You still need a nonce, and to check that what is in $_POST is what you expect, otherwise you have opened a security hole straight into your database. A hacker could put a value such that all posts get deleted in your query, or that a malware is written to a post. Never leave opportunities for misuse open and unguarded.

    Thread Starter courtneyjouning

    (@courtneyjouning)

    And to add the nonce, I have added:

    .’ajax_object.ajax_nonce’ to the data parameter,

    and

    check_ajax_referer( ‘video_nonce’, ‘security’ );
    $params = array(
    ‘ajaxurl’ => admin_url(‘admin-ajax.php’, $protocol),
    ‘ajax_nonce’ => wp_create_nonce(‘video_nonce’),
    );
    wp_localize_script( ‘my_blog_script’, ‘ajax_object’, $params );

    to the function

    I am now getting -1 when returning the form..

    Thread Starter courtneyjouning

    (@courtneyjouning)

    Actually wrapped my PHP function in an if statement to verify the nonce

    function video_filter_function(){
    $nonce = $_POST[‘_wpnonce’];
    if ( ! wp_verify_nonce( $nonce, ‘my-nonce’ ) ) {
    die( ‘Security check’ );
    } else {
    $args = array(
    ‘orderby’ => ‘date’, // we will sort posts by date
    ‘order’ => $_POST[‘date’] // ASC или DESC
    );
    // for taxonomies / categories
    if( isset( $_POST[‘categoryfilter’] ) )
    $args[‘tax_query’] = array(
    array(
    ‘taxonomy’ => ‘category’,
    ‘field’ => ‘id’,
    ‘terms’ => $_POST[‘categoryfilter’]
    )
    );
    $query = new WP_Query( $args );
    if( $query->have_posts() ) :
    while( $query->have_posts() ): $query->the_post();
    echo ‘<h2>’ . $query->post->post_title . ‘</h2>’;
    endwhile;
    wp_reset_postdata();
    else :
    echo ‘No posts found’;
    endif;
    die();
    }
    }
    add_action(‘wp_ajax_myfilter’, ‘video_filter_function’);

    then added the nonce variable to the end of the action but am receiving a 404

    The names have to match up. I don’t know what you mean by “added the nonce variable to the end of the action”.
    The nonce should be it’s own named variable.
    The action variable tells admin-ajax what action to fire, which calls your PHP function.
    You are using $_POST[‘date’], but never setting it. (and not sanitizing it)
    You need to sanitize $_POST[‘categoryfilter’]. You can use absint.
    You should use check_ajax_referer. Its parameters are the nonce value first and then the name of the nonce variable. So, your previous attempt looks better than this last one. You probably will want to add_action for the nopriv hook also, so it will be there for logged out users.

    Thread Starter courtneyjouning

    (@courtneyjouning)

    Think I have it sending correctly now, just put <?php wp_nonce_field( ‘my_nonce’ ); ?> in my form, then in the PHP function
    if (!check_ajax_referer( ‘my_nonce’ )){
    wp_die();
    }else{

    my function

    }

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Category Filtering with AJAX error’ is closed to new replies.