ajax stopped working when not logged in wordpress

Question

My code works fine if user login but not work when log out

functions.php

//ajax search --
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'POST',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>

<?php
}
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
    $the_query = new WP_Query( array( 'posts_per_page' => 5, 's' => esc_attr( $_POST['keyword'] ) ) );
    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <div class="post-box-search">
              <a href="<?php echo esc_url( post_permalink() ); ?>">
                <?php the_post_thumbnail( 'index_post' );  ?>
                <h3><?php the_title();?></h3>
              </a>
            </div>

        <?php endwhile;
        wp_reset_postdata();
    endif;
    die();
}





 ?>
0
Mohammad 4 months 0 Answers 16 views 0

Leave an answer