Custom Post type Ajax search

I’m trying to return search results without reloading the page, using ajax.

I followed some tutorials, but i can’t find a way to return the results, it loads, stops, but doesn’t return anything.

If i output the response as an alert it actually returns something, part of the site header, i have no idea why.

i’ll be grateful if someone knows what is wrong with my code.

<div id=”search-container”>
<form method=”post”>
<input type=”search” name=”ajax-search” id=”ajax-search”>
<input type=”button” name=”submit” id=”submit” value=”Buscar”>
</form>
</div>
<div class=”#content”></div>

$(document).ready(function() {
$(‘#search-container form’).on(‘submit’, function() {
var $form = $(this);
var $input = $form.find(‘input[name=”ajax-search”]’);
var query = $input.val();
var $content = $(‘#content’)

$.ajax({
type : ‘post’,
url : ‘myAjax.ajaxurl’,
data : {
action : ‘load_search_results’,
query : query
},
beforeSend: function() {
$input.prop(‘disabled’, true);
$content.addClass(‘loading’);
},
success : function( response ) {
$input.prop(‘disabled’, false);
$content.removeClass(‘loading’);
$content.append( response );
}
});

return false;
})
});

function ajax_search_enqueues() {
wp_enqueue_script( ‘ajax-search’, get_stylesheet_directory_uri() .

‘/assets/js/ajax-search.js’, array( ‘jquery’ ), ‘1.0.0’, true );
wp_localize_script( ‘ajax-search’, ‘myAjax’, array( ‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ) ) );
}
add_action( ‘wp_enqueue_scripts’, ‘ajax_search_enqueues’ );

function load_search_results() {
$query = isset($_POST[‘query’]) ? $_POST[‘query’] : ”;

$args = array(
‘post_type’ => ‘product’,
‘s’ => $query
);
$search = new WP_Query( $args );

if ( $search->have_posts() ) :
while ( $search->have_posts() ) : $search->the_post(); ?>
<h2><a href=”<?php echo esc_url( post_permalink() ); ?>”><?php the_title();?></a></h2>
<?php
endwhile;
else :
echo “Nada encontrado”;
endif;

die();
}
add_action( ‘wp_ajax_load_search_results’, ‘load_search_results’ );
add_action( ‘wp_ajax_nopriv_load_search_results’, ‘load_search_results’ );

Read more here:: Custom Post type Ajax search

Leave a Reply

Your email address will not be published. Required fields are marked *