serii
serii

Reputation: 87

How to get data from wordpress ajax search form?

My form html code, where i set action and the attribute name.

<div class="search_form">
    <form action="<?php esc_url( home_url( '/' ) ); ?>" method="POST">
        <input type="text" name="s" value="<?php get_search_query(); ?>" placeholder="Search...">
        <input type="submit" value="Send">
    </form>
</div>

I use localize scripts to connect ajax-search.

    wp_enqueue_script( 'wc-estore-ajax-search-js', get_template_directory_uri() . '/assets/js/ajax-search.js', array( 'jquery' ), _S_VERSION, true );
    wp_localize_script( 'wc-estore-ajax-search-js', 'search_form', array(
        'url'   => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( 'search-nonce' )
    ) );

In ajax-search got nonce, set action and set url.

jQuery(function ($) {
    $('.search_form input[name="s"]').on('keyup', function () {
        let search = $('.search_form input[name="s"]').val();
        if (search.length < 4) {
            return false;
        }
        let data = {
            s: search,
            action: 'search_action',
            nonce: search_form.nonce

        };
        $.ajax({
            url: search_form.url,
            data: data,
            type: 'POST',
            dataType: 'json',
            beforeSend: function (xhr) {
            },
            success: function (data) {
                console.log(data);
            }
        });

    });
});

And in functions.php i want to see, what is in $_POST. The action is the same as in the search-ajax.js.

add_action( 'wp_ajax_search_action', 'esp_search_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_search_action', 'esp_search_ajax_action_callback' );
function esp_search_ajax_action_callback() {
    /**
     * Проверяем нонсе из массива пости и из wp_localize script
     */
    if(!wp_verify_nonce($_POST['nonce'], 'search-nonce')){
        wp_die('Данные пришли с левого адреса');
    }
    $_POST = filter_input_array( INPUT_POST, FILTER_SANITIZE_STRING );
    $args = [
        'post_type' => ['post', 'product'],
        'post_status' => 'public',
        's' => $_POST['s'],
    ];

    $query_ajax = new WP_Query($args);
    ?>
    <?php if($query_ajax->have_posts()): ?>
        <?php while($query_ajax->have_posts()): ?>
            <?php $query_ajax->the_post(); ?>
            <h3 class="title-search"><?php the_title(); ?></h3>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); ?>
    <?php endif; ?>

<?php
}

But the console is clear?

Where is my mistake?

Thanks for help.

Upvotes: 0

Views: 935

Answers (1)

Phil F
Phil F

Reputation: 702

Looks like you have a few things going on. Try these:

  • dataType is the type of data you're expecting back. You're not passing valid JSON back, so it is failing with a parse error (i.e. no success, no console.log).
  • vardump probably should be var_dump unless you've defined it elsewhere. If not, that's probably causing an error and sending back the error string (which again would not be valid JSON)
  • Although not necessarily the issue you're asking about, but you should also finish your callback with wp_die(); and pass whatever parameters you need for your situation.

If you want, while you're testing you can switch dataType to html.

You can also add in error (to see what the error is) and complete (to see that it actually came back) callbacks.

And just to be safe, you might want to filter your $_POST data with something like this:

$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

or whatever filters fit your situation.

Upvotes: 1

Related Questions