How to use Jquery to retrieve ajax search results for wordpress

前端 未结 2 1084
孤街浪徒
孤街浪徒 2021-02-02 02:46

I need to set up wordpress ajax search results but my method isn\'t retrieving the results when the button is clicked and is instead redirecting me to another site ( myurl.com?s

2条回答
  •  天涯浪人
    2021-02-02 03:13

    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(response){
                    $('#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
    }
    

提交回复
热议问题