0

I'm trying to make a search bar that will search all my blogs in a wordpress site. I keep getting two errors. I'm wondering if it has something to do with they url in the ajax call. The first is a 400 in red with my local url and/wp-admin/admin-ajax.php at the end. The other is the actual error from the ajax call that says [object Object].

Here is a screenshot: enter image description here

js file:

 $(document).on("submit", "[data-js-form=search]", function (e) {
    e.preventDefault();
    let data = $(this).serialize();
    $.ajax({
      url: "/wp-admin/admin-ajax.php",
      data: data,
      type: "post",
      success: function (result) {
        console.log(result);
        $("#blog-result").html(result);
      },
      error: function (result) {
        console.warn("error :" + result);
        console.log(data);
      },
    });
  });

and my filter.php:

<?php

add_action('wp_ajax_nopriv_filter', 'filter_ajax');
add_action('wp_ajax_filter', 'filter_ajax');

function filter_ajax()

{
    $blog_search = $_POST['search'];
    print_r($_POST);

    if (!empty($blog_search)) {
        $args['s'] = $blog_search;
    }

    $query = new WP_Query($args);
    // start the loop
    if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
?>
            <li><?php echo get_the_title(); ?></li>

    <?php endwhile;
    endif; ?>
<?php wp_reset_query();

    die();
}

and the markup with the form:

<aside class="blog-search-container">
                <form data-js-form="search">
                    <fieldset>
                        <label for="search"></label>
                        <input type="text" id="search" name="search" placeholder="Search Blogs">
                    </fieldset>
                    <fieldset>
                        <button>Search</button>
                        <input type="hidden" name="action" value="Search">
                    </fieldset>
                </form>
            </aside>

Does anyone know what I'm doing wrong? Any help would be greatly appreciated!!

RRhodes
  • 501
  • 6
  • 19

1 Answers1

0

The first argument to the error: function is the jqXHR object, not the error message. When you concatenate this to "Error:" you get [object Object]; see What does [object Object] mean?

The error message is in the third argument.

error: function(jqXHR, status, error) {
    console.warn("Error: " + error);
    console.log(data);
Barmar
  • 741,623
  • 53
  • 500
  • 612