How to use jQuery to get ajax search results for wordpress

I need to customize the wordpress ajax search results, but my method does not retrieve the results when I click the button and instead redirects me to another site (myurl.com?s=term). I called admin-ajax.php correctly, but installed it incorrectly. Any ideas that are causing the problem?

//Script to activate ajax jQuery(document).ready(function($){ var search_val=$("#s").val(); $('#searchsubmit').click(function(){ $.post( WPaAjax.ajaxurl, { action : 'wpa56343_search', search_val : search_val }, function( response ) { $('#results').append( response ); } ); }); }); //function to setup wp_query add_action('wp_ajax_wpa56343_search', 'wpa56343_search'); function wpa56343_search(){ global $wp_query; $search = $_POST['search_val']; $args = array( 's' => $search, 'posts_per_page' => 5 ); $wp_query = new WP_Query( $args ); get_template_part( 'search-results' ); exit; } //html <div id="my_search"> <form role="search" method="get" id="searchform" action="http://myurl.com/" > <input type="text" value="" name="s" id="s" /> <input type="submit" id="searchsubmit" value="Search" /> </form> </div> <div id="results"></div> 
+6
source share
2 answers

You should wrap your code in document.ready

 $(document).ready(function(){ $("#searchsubmit").click(function(e){ e.preventDefault(); var search_val=$("#s").val(); $.post(search.php,{search_string:search_val},function(data){ if(data.length>0){ $("#results").html(data); } }); }); }); 

Update:

 $(document).ready(function(){ $("#searchsubmit").click(function(e){ e.preventDefault(); var search_val=$("#s").val(); $.ajax({ type:"POST", url: "./wp-admin/admin-ajax.php", data: { action:'wpa56343_search', search_string:search_val }, success:function(data){ $('#results').append(response); } }); }); 

In your functions.php

 add_action('wp_ajax_nopriv_wpa56343_search', 'wpa56343_search'); // for not logged in users add_action('wp_ajax_wpa56343_search', 'wpa56343_search'); function wpa56343_search() { // code } 
+10
source

You can also use the jQuery typeahead.js plugin, read this complete guide for more information:

http://wp.tutsplus.com/tutorials/plugins/enhancing-the-search-form-with-typeahead-js/

+1
source

Source: https://habr.com/ru/post/918815/


All Articles