Answer the question
In order to leave comments, you need to log in
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')
]);
add_action( 'wp_ajax_search_ajax', 'searchAjax' );
add_action( 'wp_ajax_nopriv_search_ajax', 'searchAjax' );
function searchAjax(){
var_dump($_POST);
}
(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);
Answer the question
In order to leave comments, you need to log in
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);
}
});
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 questionAsk a Question
731 491 924 answers to any question