0

I'm developing a custom plugin that implements an ajax-powered search form on a WordPress site. It runs a WordPress query and outputs the results just below the search box where a user types their search string. Locally in my development environment, the plugin works fine. But when I install it on my production server it does not work. According to the Chrome dev tools, the XHR action for my form submission is returning 200 status but the response says No response data available for this request. The ajax error does not get logged to the console so the request isn't failing.

I have no direct access to the server so I can't change or check those settings, I'm assuming it's something blocking the action from running? I had requested the server administrators to check for any issues with my action running on their server and they said they had resolved this but I'm still having the issue.

This is my code:

add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');

function data_fetch(){
    $max_posts = -1;
    $the_query = new WP_Query( array( 'posts_per_page' => $max_posts, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'rrm_safety', 'orderby' => 'title', 'order' => 'ASC' ));

    if( $the_query->have_posts() ) :
        $results = "";

        foreach($the_query->posts as $result)
        {
            $results.= '<div><a href="'.get_permalink($result->ID).'">'.$result->post_title.'</a></div>';           
        }   
        print $results;
    else: 
        print '<div>No results</div>';  
    endif;

    die();
}

add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">

    jQuery(document).ready(main);
    
    function main(){
        //create a div where we can dynamically send results
        jQuery('#topics-search').append('<div id="ajax_search_results_go_here"></div>');
        jQuery('#ajax_search_results_go_here').hide();
        
        //listen for changes in our search field
        jQuery('#topics-search #search').keyup(get_search_results);
        
      jQuery(window).keydown(function(event){
        if( event.keyCode == 13) {
          event.preventDefault();
          return false;
        }
      });

    }
    
    function get_search_results(){              
        var keyword = jQuery('#topics-search #search').val();       
        if(keyword == ""){
            jQuery('#ajax_search_results_go_here').html("");
        } else {
            jQuery.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: { action: 'data_fetch', keyword: keyword  },
                success: function(data) {
                    jQuery('#ajax_search_results_go_here').html( data );
                    jQuery('#ajax_search_results_go_here').slideDown( 400 );
                },
                error: function (error) {
                    console.log(error);
                }
            });
        }   
    }
</script>

5
  • are you sure it isn't failing? Have you checked the PHP error log? -1 is a very dangerous value for posts per page, as you could get far more posts than you can handle. Also is there a reason you're returning HTML from a custom endpoint on the old legacy admin ajax API rather than pulling in data straight from the official example.com/wp-json/wp/v2/posts endpoint in the REST API and creating the HTML in JS? It would be more secure, faster, and save you writing PHP code. example.com/wp-json/wp/v2/rrm_safety?s=keyword&orderby=title&order=asc? Assuming you have show_in_rest set to true
    – Tom J Nowell
    Nov 30 '21 at 0:56
  • Thanks for your answer Tom. I'm not familiar with this new way of using the REST API instead of the Ajax call. I'll have to look into that. Thanks!
    – mruboy
    Nov 30 '21 at 1:33
  • eh not an answer, just a comment
    – Tom J Nowell
    Nov 30 '21 at 9:40
  • Well I did attempt to use the REST API but unfortunately, on the WordPress production server there is the iThemes security plugin that is set to restrict REST API so my solution won't work for that reason. I don't have control over those iThemes settings and I don't think the people in charge will wish to change that. Unless there's some way around this restriction for this specific plugin? As far as I can tell it's all or nothing.
    – mruboy
    Dec 1 '21 at 2:32
  • you would need to ask iThemes about that, though without the REST API lots of things won't work, e.g. the block editor, OEmbed of WP posts, etc ( curious that they would restrict the more secure API and leave the less secure API unrestricted )
    – Tom J Nowell
    Dec 1 '21 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.