Using AJAX to return search form results

There are two issues in your code

You need to add script in wp_enqueue_scripts hooks like this –

add_action('wp_enqueue_scripts', 'my_custom_js_script');

function my_custom_js_script() {
    wp_register_script( 'ajax-productSearch', get_template_directory_uri() .'/js/ajax-product-search.js', array( 'jquery') );
    wp_enqueue_script( 'ajax-productSearch' );
    wp_localize_script( 'ajax-productSearch','the_ajax_productSearch', array('ajaxurl_productSearch' => admin_url('admin-ajax.php')));
}

The second issue is that, you need to add action argument in your jQuery.ajax data. If your hook is wp_ajax_my_ajax_hook, the value of this argument will be my_ajax_hook. In your case, it will be productSearch. Change your product_search function to this –

function product_search(){
  jQuery.ajax({
    data: { action: 'productSearch', formData: jQuery('#product_search_form').serialize() },
    type: jQuery('#product_search_form').attr('method'),
    url:  the_ajax_productSearch.ajaxurl_productSearch,
    beforeSend: function(){
      jQuery('#product_search_form_content').remove();
      jQuery('#product_search_form').append('<div class="alert alert-success" role="alert" align="center"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Loading...</div>');
    },

    success: function(response) { // on success..
      jQuery('#product_search_form').html(response);
    },
  });
  return false; // cancel original event to prevent form submitting
}

Leave a Comment