S
S
Sergey Burduzha2020-07-02 10:15:49
WordPress
Sergey Burduzha, 2020-07-02 10:15:49

Why is ajax request not working in wordpress?

Good afternoon.
It seems to have done everything as in the documentation, but for some reason I can not get data from the search form.

<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>


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', [
    'url' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('search-nonce')
  ]);


functions.php

add_action( 'wp_ajax_search_ajax', 'searchAjax' );
add_action( 'wp_ajax_nopriv_search_ajax', 'searchAjax' );

function searchAjax(){
  var_dump($_POST);
}


And the js code itself
(function ($) {
  $(function () {
    $('.search_form input[name="s"]').on('keyup', function () {
      let searchInput = $(this).val();
      if (searchInput.length < 4) {
        return false;
      }
      $.ajax({
        url: search.url,
        data: {
          s: searchInput,
          action: 'search_ajax', //событие на которой повесим функцию обработчик
          nonce: search.nonce // nonce из объекта из wp_localize_script
        },
        type: 'POST',
        dataType: 'json',
        beforeSend: function (xhr) {

        },
        success: function (data) {
          console.log(data);
        }
      });
    });
  });
})(jQuery);


What's wrong, I've been sorting through the code for half an hour, looking at other errors on the network, it seems that the nonce is correct and the ajax hooks too.
Somewhere there is an error.

Thanks in advance for the hint.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Burduzha, 2020-07-02
@serii81

Found a solution.
json didn't work for me, I used html.

jQuery.ajax({
      type: 'POST',
      url: search_form.url,
      data: data,
      dataType: 'html',
      success: function (data) {
        $('.search_form .search-result').html(data);
      }
    });

And then I filtered it in functions.php and output
add_action( 'wp_ajax_myaction', 'esp_search_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_myaction', '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
    wp_die();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question